### Expr Basic Usage Example Source: https://github.com/expr-lang/expr/blob/master/README.md A basic Go example demonstrating how to compile and run an Expr expression with a custom environment. ```go package main import ( "fmt" "github.com/expr-lang/expr" ) func main() { env := map[string]interface{}{ "greet": "Hello, %v!", "names": []string{"world", "you"}, "sprintf": fmt.Sprintf, } code := `sprintf(greet, names[0])` program, err := expr.Compile(code, expr.Env(env)) if err != nil { panic(err) } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Println(output) } ``` -------------------------------- ### Install Expr Expression Language Source: https://github.com/expr-lang/expr/blob/master/README.md Standard Go installation command for the Expr library. ```bash go get github.com/expr-lang/expr ``` -------------------------------- ### Expr Example: Conditional Access Source: https://github.com/expr-lang/expr/blob/master/README.md This example demonstrates how to use Expr to conditionally allow access based on user roles. ```js // Allow only admins and moderators to moderate comments. user.Group in ["admin", "moderator"] || user.Id == comment.UserId ``` -------------------------------- ### Expr 'all' Function Example Source: https://github.com/expr-lang/expr/blob/master/README.md This Go example demonstrates using the 'all' function in Expr to check if all elements in a slice meet a condition, with custom types. ```go package main import ( "fmt" "github.com/expr-lang/expr" ) type Tweet struct { Len int } type Env struct { Tweets []Tweet } func main() { code := `all(Tweets, {.Len <= 240})` program, err := expr.Compile(code, expr.Env(Env{})) if err != nil { panic(err) } env := Env{ Tweets: []Tweet{{42}, {98}, {69}}, } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Println(output) } ``` -------------------------------- ### Sorting and Summation Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of `sortBy` for custom sorting and `sum` for calculating totals. ```expr sort($env) | sortBy(#) ``` ```expr sort($env) | sortBy(#.String) ``` ```expr sort($env) | sortBy(.add) ``` ```expr sort($env) | sortBy(.f64) ``` ```expr sort($env) | sortBy(1.0) ``` ```expr sort($env) | sortBy(foo) ``` ```expr sort($env) | sortBy(i) ``` ```expr sort($env) | sortBy(str) ``` ```expr sort($env) | sum(#.foo) ``` ```expr sort($env) | sum(#.greet) ``` ```expr sort($env) | sum(#.str?.String) ``` ```expr sort($env) | sum($env) ``` ```expr sort($env) | sum(.array) ``` ```expr sort($env) | sum(1.0) ``` ```expr sort($env) | sum(array) ``` ```expr sort($env) | sum(false) ``` ```expr sort($env) | sum(foo) ``` ```expr sort($env) | sum(not #.array) ``` -------------------------------- ### Range and Literal Expressions Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of creating ranges and using literal values in expressions. ```expr sort(0 .. i) ``` ```expr sort(0 ?? 1.0) ``` ```expr sort(0 ?? foo) ``` ```expr sort(0 ?? foo.Bar) ``` ```expr sort(0 ?? ok) ``` ```expr sort(1 .. 1) ``` ```expr sort(1 ?? 1.0) ``` ```expr sort(1 ?? array) ``` ```expr sort(1 ?? false) ``` ```expr sort(1 ?? foo) ``` ```expr sort(1 ?? greet) ``` ```expr sort(1 ?? ok) ``` ```expr sort(1..i) ``` ```expr sort(1.0 ?? $env) ``` ```expr sort(1.0 ?? 0) ``` ```expr sort(1.0 ?? false) ``` ```expr sort(1.0 ?? foo) ``` ```expr sort(1.0 ?? greet) ``` ```expr sort(1.0 ?? i) ``` ```expr sort(1.0 ?? ok) ``` ```expr sort(1.0 ?? str) ``` ```expr sort(1.0 ?? true) ``` -------------------------------- ### Expr Example: Time Window Check Source: https://github.com/expr-lang/expr/blob/master/README.md This example shows how to use Expr to determine if a request falls within a permitted time window. ```js // Determine whether the request is in the permitted time window. request.Time - resource.Age < duration("24h") ``` -------------------------------- ### Expr Example: All Elements Condition Source: https://github.com/expr-lang/expr/blob/master/README.md This example demonstrates using the 'all' built-in function in Expr to check if all elements in a collection satisfy a condition. ```js // Ensure all tweets are less than 240 characters. all(tweets, len(.Content) <= 240) ``` -------------------------------- ### Type Checking with Environment Source: https://github.com/expr-lang/expr/blob/master/docs/getting-started.md Demonstrates how Expr infers and type-checks expressions against the provided environment. This example will panic due to a type mismatch. ```go env := map[string]any{ "name": "Anton", "age": 35, } program, err := expr.Compile(`name + age`, expr.Env(env)) if err != nil { // highlight-next-line panic(err) // Will panic with "invalid operation: string + int" } ``` -------------------------------- ### String Concatenation Source: https://github.com/expr-lang/expr/wiki/The-Expression-Syntax Use the '~' operator for string concatenation. This example concatenates three strings with a space in between. ```go 'Arthur' ~ ' ' ~ 'Dent' ``` -------------------------------- ### Check if string starts with a prefix Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Use `hasPrefix` to determine if a string begins with a specified prefix. ```expr hasPrefix("HelloWorld", "Hello") == true ``` -------------------------------- ### Variable Assignment and Usage Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Demonstrates assigning values to variables using `let` and then using these variables in subsequent expressions. Includes examples with different data types and conditional assignments. ```expr let bar = $env == f64; bar ``` ```expr let bar = $env.f64; bar ``` ```expr let bar = $env.str; bar ``` ```expr let bar = $env; bar.array ``` ```expr let bar = $env; bar.foo ``` ```expr let bar = $env?.list; bar ``` ```expr let bar = 0 == $env; bar ``` ```expr let bar = 1 == $env; bar ``` ```expr let bar = [1.0]; bar ``` ```expr let bar = add; bar ``` ```expr let bar = array == list; bar ``` ```expr let bar = array ?? foo; bar ``` ```expr let bar = array; bar ``` ```expr let bar = f64; bar ``` ```expr let bar = f64; bar + f64 ``` ```expr let bar = f64; let tmp = add; bar ``` ```expr let bar = foo ?? f64; bar ``` ```expr let bar = foo.Bar; bar ``` ```expr let bar = foo.Bar; let x = add; bar ``` ```expr let bar = foo.String(); bar ``` ```expr let bar = foo; bar ``` ```expr let bar = foo; bar.String ``` ```expr let bar = greet ?? i; bar ``` ```expr let bar = greet; bar ``` ```expr let bar = i; bar ``` ```expr let bar = i; let z = !ok; bar ``` ```expr let bar = list; bar ``` ```expr let bar = list; let foobar = greet; bar ``` ```expr let bar = list[1:]; bar ``` ```expr let bar = nil != add; bar ``` ```expr let bar = ok == true; bar ``` ```expr let bar = ok; bar ``` ```expr let bar = str; bar ``` ```expr let bar = str; let foobar = greet; bar ``` ```expr let bar = string($env); bar ``` ```expr let bar = type(f64); bar ``` ```expr let foobar = $env not in array; foobar ``` ```expr let foobar = $env.f64; i < foobar ``` ```expr let foobar = $env.list; foobar ``` ```expr let foobar = $env.str; foobar ``` ```expr let foobar = $env; foobar == foobar ``` ```expr let foobar = $env; foobar.Bar ``` ```expr let foobar = $env; foobar.String ``` ```expr let foobar = $env; foobar.add ``` ```expr let foobar = $env; foobar.foo ``` ```expr let foobar = $env; foobar.greet ``` ```expr let foobar = $env; foobar.list ``` ```expr let foobar = $env; foobar.ok ``` ```expr let foobar = $env; foobar.str ``` ```expr let foobar = $env; foobar?.[str] ``` ```expr let foobar = $env; foobar?.add ``` ```expr let foobar = $env; foobar?.foobar ``` ```expr let foobar = $env; foobar?.greet ``` ```expr let foobar = $env; foobar?.i ``` ```expr let foobar = $env; foobar?.list ``` ```expr let foobar = $env; foobar?.str ``` ```expr let foobar = $env?.Bar; foobar ``` ```expr let foobar = $env?.String; foobar ``` ```expr let foobar = $env?.[Bar]; foobar?.list ``` ```expr let foobar = $env?.[String]; foobar ``` ```expr let foobar = $env?.[String]; foobar?.[str] ``` ```expr let foobar = $env?.[str]; foobar ``` ```expr let foobar = $env?.f64; foobar > foobar ``` ```expr let foobar = $env?.true; foobar ``` ```expr let foobar = 0 + f64; foobar ``` ```expr let foobar = 0; foobar != foobar ``` ```expr let foobar = 0; foobar <= foobar ``` ```expr let foobar = 1 * 1.0; foobar ``` ```expr let foobar = 1.0 != 1.0; foobar ``` ```expr let foobar = 1.0; foobar * foobar ``` ```expr let foobar = 1; foobar != f64 ``` ```expr let foobar = 1; foobar % foobar ``` ```expr let foobar = 1; foobar < float(foobar) ``` ```expr let foobar = add; $env != foobar ``` ```expr let foobar = add; foobar ``` ```expr let foobar = array | sortBy(1.0); foobar ``` ```expr let foobar = array; foobar ``` ```expr let foobar = array; foobar?.[0] ``` ```expr let foobar = array; foobar?.[i] ``` ```expr let foobar = array; let bar = foobar; foobar ``` ```expr let foobar = array?.[i]; f64 + foobar ``` ```expr let foobar = f64 ?? nil; foobar ``` ```expr let foobar = f64; foobar ``` -------------------------------- ### Array and List Operations Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples showcasing operations on arrays and lists, including comparisons, filtering, mapping, grouping, and sorting. ```expr concat(array) == array ``` ```expr concat(array) == list ``` ```expr concat(array) | all(ok) ``` ```expr concat(array) | any(false) ``` ```expr concat(array) | any(ok) ``` ```expr concat(array) | count(1.0 >= f64) ``` ```expr concat(array) | count(ok) ``` ```expr concat(array) | groupBy(#) ``` ```expr concat(array) | groupBy(0) ``` ```expr concat(array) | groupBy(1.0) ``` ```expr concat(array) | groupBy(true) ``` ```expr concat(array) | map(0) ``` ```expr concat(array) | map(1.0) ``` ```expr concat(array) | map(f64) ``` ```expr concat(array) | map(list) ``` ```expr concat(array) | map(ok) ``` ```expr concat(array) | max(1.0) ``` ```expr concat(array) | reduce(#) ``` ```expr concat(array) | reduce(1, foo) ``` ```expr concat(array) | reduce(str) ``` ```expr concat(array) | sortBy(f64) ``` ```expr concat(array) | sum(#) ``` ```expr concat(array)?.[i] ``` ```expr concat(list) == [1, str] ``` ```expr concat(list) | any(ok) ``` ```expr concat(list) | count(false) ``` ```expr concat(list) | findIndex(true) ``` ```expr concat(list) | groupBy(#) ``` ```expr concat(list) | groupBy(0) ``` ```expr concat(list) | groupBy(1) ``` ```expr concat(list) | groupBy(1.0) ``` ```expr concat(list) | groupBy(foo) ``` ```expr concat(list) | map(0) ``` ```expr concat(list) | map(add) ``` ```expr concat(list) | map(f64) ``` ```expr concat(list) | map(foo) ``` ```expr concat(list) | none(ok) ``` ```expr concat(list) | reduce(#) ``` ```expr concat(list) | reduce(1.0, foo) ``` ```expr concat(list) | reduce(f64) ``` ```expr concat(list) | reduce(foo) ``` ```expr concat(list) | reduce(i, str) ``` ```expr concat(list) | sum(1) ``` ```expr concat(list) | sum(i) ``` ```expr concat(list)?.[i] ``` ```expr concat(list, $env.array) ``` ```expr concat(list, array) ``` ```expr concat(list, array)?.[i] ``` ```expr concat(list, list | sortBy(i)) ``` ```expr concat(list, list) ``` ```expr concat(list, list) | any(true) ``` ```expr concat(list, list)?.[i] ``` ```expr concat(list[1:]) ``` ```expr concat(map($env, #index)) ``` ```expr concat(map($env, $env)) ``` ```expr concat(map($env, 1.0)) ``` ```expr concat(map($env, array)) ``` ```expr concat(map($env, array), list) ``` ```expr concat(map($env, f64)) ``` ```expr concat(map($env, foo)) ``` -------------------------------- ### Array Transformation and Aggregation Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of `concat`, `count`, `filter`, `find`, and `findIndex` for manipulating array data. ```expr sort($env) | concat(list) ``` ```expr sort($env) | count(#) ``` ```expr sort($env) | count(#.Bar) ``` ```expr sort($env) | count(#.foo) ``` ```expr sort($env) | count(#.i == 0) ``` ```expr sort($env) | count($env) ``` ```expr sort($env) | count(.f64) ``` ```expr sort($env) | count(false) ``` ```expr sort($env) | filter(#) ``` ```expr sort($env) | filter(#.String) ``` ```expr sort($env) | filter(#.i) ``` ```expr sort($env) | filter(#.list) ``` ```expr sort($env) | find(#) ``` ```expr sort($env) | find(#.Bar) ``` ```expr sort($env) | find(#.list) ``` ```expr sort($env) | find($env) ``` ```expr sort($env) | find(.String[#.array:true]) ``` ```expr sort($env) | find(.array) ``` ```expr sort($env) | find(.i) ``` ```expr sort($env) | find(false) ``` ```expr sort($env) | findIndex(#) ``` ```expr sort($env) | findIndex(#.add) ``` ```expr sort($env) | findIndex(#.array) ``` ```expr sort($env) | findIndex(.String) ``` ```expr sort($env) | findIndex(.array) ``` ```expr sort($env) | findIndex(.foo) ``` ```expr sort($env) | findIndex(.ok) ``` ```expr sort($env) | findIndex(false) ``` ```expr sort($env) | findIndex(ok) ``` -------------------------------- ### Array Indexing and Property Access Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of accessing array elements by index and accessing properties of objects within arrays. ```expr sort($env)?.[i] ``` ```expr sort($env)?.[i].add() ``` ```expr sort($env)?.[i]?.[array] ``` ```expr sort($env)[:] ``` ```expr sort($env.array) ``` ```expr sort($env?.$env) ``` ```expr sort($env?.Bar) ``` ```expr sort($env?.Bar?.[ok]) ``` ```expr sort($env?.Bar?.greet) ``` ```expr sort($env?.String) ``` ```expr sort($env?.String) | one(.str.add(foobar)) ``` ```expr sort($env?.[Bar]) ``` ```expr sort($env?.[Bar]) ?? array ``` ```expr sort($env?.[Bar]?.[array]) ``` ```expr sort($env?.[Bar]?.foo()) ``` ```expr sort($env?.[String]) ``` ```expr sort($env?.[foobar]) ``` ```expr sort($env?.[foobar]?.[add]) ``` ```expr sort($env?.[nil]) ``` ```expr sort($env?.[nil]?.String().array) ``` ```expr sort($env?.[str]) ``` ```expr sort($env?.array) ``` ```expr sort($env?.false) ``` ```expr sort($env?.foobar) ``` ```expr sort($env?.foobar?.greet) ``` ```expr sort($env?.list | reduce(#acc)) ``` ```expr sort($env?.nil) ``` -------------------------------- ### Conditional and Reduce Operations Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples demonstrating the use of the nil-coalescing operator (??) and the reduce function for aggregation. ```expr ceil(nil ?? 1) ``` ```expr ceil(nil ?? i) ``` ```expr ceil(reduce($env, 1, $env)) ``` ```expr ceil(reduce(array, #)) ``` ```expr ceil(reduce(array, #acc)) ``` ```expr ceil(reduce(array, 1.0)) ``` ```expr ceil(reduce(array, f64)) ``` ```expr ceil(reduce(list, 0)) ``` ```expr ceil(reduce(list, 1)) ``` -------------------------------- ### Get current year Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Use `now()` to get the current date and time, then call methods like `Year()` to extract specific components. ```expr now().Year() == 2024 ``` -------------------------------- ### Object Property Access Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of accessing object properties using dot notation and the safe navigation operator (?. or ?.). ```expr ceil({foo: 1.0}?.foo) ``` -------------------------------- ### String Concatenation Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of the concat function used for joining strings, arrays, and other data types. ```expr concat($env | map(1.0)) ``` ```expr concat($env | map(1.0))[:i] ``` ```expr concat($env | map(add)) ``` ```expr concat($env | map(array)) ``` ```expr concat($env | map(foo)) ``` ```expr concat($env | map(greet)) ``` ```expr concat($env.array) ``` ```expr concat($env.list) ``` ```expr concat($env?.array | sortBy(#)) ``` ```expr concat($env?.array) ``` ```expr concat($env?.list) ``` ```expr concat(0 .. 1) ``` ```expr concat(0 .. i) ``` ```expr concat(1 .. 0) ``` ```expr concat(1 .. 1) ``` ```expr concat(1 .. i) ``` ```expr concat(1..i) ``` ```expr concat([$env, $env]) ``` ```expr concat([$env, 1]) ``` ```expr concat([$env, add]) ``` ```expr concat([$env, nil]) ``` ```expr concat([$env]) ``` ```expr concat([0]) ``` ```expr concat([1, foo]) ``` ```expr concat([1.0 - 1.0]) ``` ```expr concat([1.0, $env]) ``` ```expr concat([1.0]) ``` ```expr concat([1]) ``` ```expr concat([add, $env]) ``` ```expr concat([add]) ``` ```expr concat([array, 1.0]) ``` ```expr concat([array, 1]) ``` ```expr concat([array]) ``` ```expr concat([f64, foo]) ``` ```expr concat([f64]) ``` ```expr concat([false, $env]) ``` ```expr concat([false]) ``` ```expr concat([foo, 1.0]) ``` ```expr concat([foo, array]) ``` ```expr concat([foo]) ``` ```expr concat([greet, 0]) ``` ```expr concat([greet]) ``` ```expr concat([i, 1.0]) ``` ```expr concat([i]) ``` ```expr concat([list]) ``` ```expr concat([nil]) ``` ```expr concat([ok, $env]) ``` ```expr concat([ok]) ``` ```expr concat([str]) ``` ```expr concat([true, list]) ``` ```expr concat([true, str]) ``` ```expr concat([true]) ``` ```expr concat([true], array) ``` ```expr concat(array ?? $env) ``` ```expr concat(array ?? 1) ``` ```expr concat(array ?? add) ``` ```expr concat(array ?? f64) ``` ```expr concat(array ?? greet) ``` ```expr concat(array ?? nil) ``` ```expr concat(array ?? true) ``` ```expr concat(array | map(#)) ``` ```expr concat(array | map($env)) ``` ```expr concat(array | map(foo)) ``` ```expr concat(array | sortBy(#)) ``` ```expr concat(array | sortBy(f64)) ``` ```expr concat(array | sortBy(i)) ``` ```expr concat(array | take(0)) ``` ```expr concat(array) ``` ```expr concat(array, [greet]) ``` ```expr concat(array, array) ``` ```expr concat(array, array)?.[i] ``` ```expr concat(array, array, [list]) ``` ```expr concat(array, list) ``` ```expr concat(array[0:]) ``` ```expr concat(array[1:]) ``` ```expr concat(array[:0]) ``` ```expr concat(array[:1]) ``` ```expr concat(array[:]) ``` ```expr concat(array[i:]) ``` ```expr concat(concat(array)) ``` ```expr concat(concat(array, array)) ``` ```expr concat(concat(list)) ``` ```expr concat(false ?: array) ``` ```expr concat(false ?: list) ``` ```expr concat(filter($env, false)) ``` ```expr concat(flatten($env.array)) ``` ```expr concat(flatten(array)) ``` ```expr concat(flatten(list)) ``` ```expr concat(i .. 0) ``` ```expr concat(i..i) ``` ```expr concat(keys($env)) ``` ```expr concat(keys({foo: array, foo: i})) ``` ```expr concat(list ?? $env) ``` ```expr concat(list ?? 1) ``` ```expr concat(list ?? 1.0) ``` ```expr concat(list ?? foo) ``` ```expr concat(list ?? i) ``` ```expr concat(list ?? str) ``` ```expr concat(list ?? true) ``` ```expr concat(list | filter(ok)) ``` ```expr concat(list | map(#)) ``` ```expr concat(list | map($env)) ``` ```expr concat(list | map(.String)) ``` ```expr concat(list | map(1)) ``` ```expr concat(list | map(1.0)) ``` ```expr concat(list | map(foo)) ``` ```expr concat(list | map(list), array) ``` ```expr concat(list | sortBy(1.0)) ``` ```expr concat(list | sortBy(i)) ``` ```expr concat(list) ``` ```expr concat(list) | any(ok) ``` ```expr concat(list) | count(false) ``` ```expr concat(list) | findIndex(true) ``` ```expr concat(list) | groupBy(#) ``` ```expr concat(list) | groupBy(0) ``` ```expr concat(list) | groupBy(1) ``` ```expr concat(list) | groupBy(1.0) ``` ```expr concat(list) | groupBy(foo) ``` ```expr concat(list) | map(0) ``` ```expr concat(list) | map(add) ``` ```expr concat(list) | map(f64) ``` ```expr concat(list) | map(foo) ``` ```expr concat(list) | none(ok) ``` ```expr concat(list) | reduce(#) ``` ```expr concat(list) | reduce(1.0, foo) ``` ```expr concat(list) | reduce(f64) ``` ```expr concat(list) | reduce(foo) ``` ```expr concat(list) | reduce(i, str) ``` ```expr concat(list) | sum(1) ``` ```expr concat(list) | sum(i) ``` ```expr concat(list)?.[i] ``` ```expr concat(list, $env.array) ``` ```expr concat(list, array) ``` ```expr concat(list, array)?.[i] ``` ```expr concat(list, list | sortBy(i)) ``` ```expr concat(list, list) ``` ```expr concat(list, list) | any(true) ``` ```expr concat(list, list)?.[i] ``` ```expr concat(list[1:]) ``` ```expr concat(map($env, #index)) ``` ```expr concat(map($env, $env)) ``` ```expr concat(map($env, 1.0)) ``` ```expr concat(map($env, array)) ``` ```expr concat(map($env, array), list) ``` ```expr concat(map($env, f64)) ``` ```expr concat(map($env, foo)) ``` -------------------------------- ### Ternary Operator Example Source: https://github.com/expr-lang/expr/wiki/The-Expression-Syntax Illustrates the use of the ternary operator for conditional assignment. ```expr foo ? 'yes' : 'no' ``` -------------------------------- ### Finding Last Elements and Grouping Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples using `findLast`, `findLastIndex`, and `groupBy` for searching and organizing array elements. ```expr sort($env) | findLast(#) ``` ```expr sort($env) | findLast(#.array) ``` ```expr sort($env) | findLast(#.list?.foo(#)) ``` ```expr sort($env) | findLast(#.str) ``` ```expr sort($env) | findLast(false) ``` ```expr sort($env) | findLastIndex(#) ``` ```expr sort($env) | findLastIndex(#.add) ``` ```expr sort($env) | findLastIndex(#.list) ``` ```expr sort($env) | findLastIndex($env) ``` ```expr sort($env) | findLastIndex(.Bar) ``` ```expr sort($env) | findLastIndex(.foo) ``` ```expr sort($env) | groupBy(#) ``` ```expr sort($env) | groupBy(#.Bar) ``` ```expr sort($env) | groupBy(#.add) ``` ```expr sort($env) | groupBy(#.greet / #) ``` ```expr sort($env) | groupBy(#.greet) ``` ```expr sort($env) | groupBy(#?.foo(i)) ``` ```expr sort($env) | groupBy(.array) ``` ```expr sort($env) | groupBy(.greet) ``` ```expr sort($env) | groupBy(0) ``` ```expr sort($env) | groupBy(1.0) ``` ```expr sort($env) | groupBy(add) ``` ```expr sort($env) | groupBy(f64) ``` ```expr sort($env) | groupBy(i) ``` ```expr sort($env) | groupBy(list) ``` ```expr sort($env) | groupBy(ok) ``` -------------------------------- ### Traverse AST with Visitor after Parsing Source: https://github.com/expr-lang/expr/blob/master/docs/visitor.md Parse an expression string and then use `ast.Walk` to traverse the resulting AST with a custom visitor. This example collects all identifiers from the parsed expression. ```go tree, err := parser.Parse(`foo + bar`) if err != nil { panic(err) } v := &Visitor{} // highlight-next-line ast.Walk(&tree.Node, v) fmt.Println(v.Identifiers) // [foo, bar] ``` -------------------------------- ### Get Map Keys Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Returns an array containing all the keys from a map. ```expr keys({"name": "John", "age": 30}) == ["name", "age"] ``` -------------------------------- ### Get Map Values Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Returns an array containing all the values from a map. ```expr values({"name": "John", "age": 30}) == ["John", 30] ``` -------------------------------- ### Logical Expression Example Source: https://github.com/expr-lang/expr/wiki/The-Expression-Syntax Combines comparison and logical operators to form a boolean expression. ```expr life < universe or life < everything ``` -------------------------------- ### String Index Of Function Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Returns the starting index of the first occurrence of a substring within a string, or -1 if not found. ```expr indexOf("apple pie", "pie") == 6 ``` -------------------------------- ### Variable Declaration with `let` Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Declares variables using the `let` keyword. Variables must start with a letter or underscore and can contain letters, digits, and underscores. ```expr let x = 42; x * 2 ``` ```expr let x = 42; let y = 2; x * y ``` ```expr let name = user.Name | lower() | split(" "); "Hello, " + name[0] + "!" ``` -------------------------------- ### Arithmetic Expression Example Source: https://github.com/expr-lang/expr/wiki/The-Expression-Syntax Demonstrates basic arithmetic operations. All binary operators working with numbers automatically cast the result to float64. ```expr life + universe + everything ``` -------------------------------- ### Get First Element of Array Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Returns the first element from an array. Returns `nil` if the array is empty. ```expr first([1, 2, 3]) == 1 ``` -------------------------------- ### Mathematical Functions Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Examples of mathematical functions like ceil, sum, mean, max, min, and round. These functions operate on numbers and arrays. ```expr ceil(len(str)) ``` ```expr ceil(let foobar = 1.0; foobar) ``` ```expr ceil(let foobar = f64; foobar + foobar) ``` ```expr ceil(list | reduce(0)) ``` ```expr ceil(list | reduce(0, 1.0)) ``` ```expr ceil(list | reduce(f64)) ``` ```expr ceil(list | sum(i)) ``` ```expr ceil(max(0)) ``` ```expr ceil(max(1)) ``` ```expr ceil(max(1.0)) ``` ```expr ceil(max(array)) ``` ```expr ceil(max(array, 1.0)) ``` ```expr ceil(max(f64)) ``` ```expr ceil(max(f64, f64)) ``` ```expr ceil(max(i)) ``` ```expr ceil(mean(0)) ``` ```expr ceil(mean(1)) ``` ```expr ceil(mean(1.0 ^ 1.0)) ``` ```expr ceil(mean(1.0)) ``` ```expr ceil(mean(array)) ``` ```expr ceil(mean(f64)) ``` ```expr ceil(mean(f64, 1)) ``` ```expr ceil(mean(i)) ``` ```expr ceil(mean(i, i, 0)) ``` ```expr ceil(mean(mean(1.0))) ``` ```expr ceil(median(0)) ``` ```expr ceil(median(1)) ``` ```expr ceil(median(1.0)) ``` ```expr ceil(median(1.0, 0)) ``` ```expr ceil(median(1.0, array)) ``` ```expr ceil(median(1.0, i)) ``` ```expr ceil(median(array)) ``` ```expr ceil(median(f64)) ``` ```expr ceil(median(i)) ``` ```expr ceil(median(i, 1.0)) ``` ```expr ceil(min(0)) ``` ```expr ceil(min(1)) ``` ```expr ceil(min(1.0)) ``` ```expr ceil(min(1.0, f64)) ``` ```expr ceil(min(1.0, i)) ``` ```expr ceil(min(array)) ``` ```expr ceil(min(f64)) ``` ```expr ceil(min(i)) ``` ```expr ceil(round(0)) ``` ```expr ceil(round(1)) ``` ```expr ceil(round(1.0)) ``` ```expr ceil(round(f64)) ``` ```expr ceil(round(i)) ``` ```expr ceil(sum($env, f64)) ``` ```expr ceil(sum($env.array)) ``` ```expr ceil(sum(array)) ``` ```expr ceil(sum(array, #)) ``` ```expr ceil(sum(list, 1.0)) ``` ```expr ceil(sum(list, f64)) ``` -------------------------------- ### Count Elements Equivalent to Filter Length Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Demonstrates that `count` with a predicate is equivalent to filtering the array and getting its length. ```expr len(filter(users, .Age > 18)) ``` -------------------------------- ### Expr Static Typing Error Example Source: https://github.com/expr-lang/expr/blob/master/README.md This Go code snippet demonstrates a static typing error in Expr when attempting to add a string and an integer. ```go out, err := expr.Compile(`name + age`) // err: invalid operation + (mismatched types string and int) // | name + age // | .....^ ``` -------------------------------- ### Compile Expression with Integer Return Type Source: https://github.com/expr-lang/expr/blob/master/docs/configuration.md Compile an expression expecting an integer return type. Other numeric types like float64 and uint will be cast to int. This example also enables warnings for any return types. ```go program, err := expr.Compile(code, expr.AsInt(), expr.WarnOnAny()) ``` -------------------------------- ### String Last Index Of Function Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Returns the starting index of the last occurrence of a substring within a string, or -1 if not found. ```expr lastIndexOf("apple pie apple", "apple") == 10 ``` -------------------------------- ### Retrieve element from array or map Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Use get to access an element by index in an array or by key in a map. Returns nil if the index or key is out of range or does not exist. ```expr get([1, 2, 3], 1) == 2 get({"name": "John", "age": 30}, "name") == "John" ``` -------------------------------- ### Generate Markdown Documentation with DocGen Source: https://github.com/expr-lang/expr/blob/master/docgen/README.md This snippet demonstrates how to generate documentation in Markdown format. Replace 'env' with your specific types and execute the Go program. ```go package main import "github.com/expr-lang/expr/docgen" func main() { // TODO: Replace env with your own types. doc := docgen.CreateDoc(env) print(doc.Markdown()) } ``` -------------------------------- ### Reusing Compiled Programs Source: https://github.com/expr-lang/expr/blob/master/docs/getting-started.md Demonstrates reusing a compiled program with different environment instances. This is beneficial for performance in applications with frequent evaluations. ```go type Env struct { X int Y int } program, err := expr.Compile(`X + Y`, expr.Env(Env{})) if err != nil { panic(err) } output, err := expr.Run(program, Env{1, 2}) if err != nil { panic(err) } fmt.Print(output) // 3 output, err = expr.Run(program, Env{3, 4}) if err != nil { panic(err) } fmt.Print(output) // 7 ``` -------------------------------- ### Generate JSON Documentation with DocGen Source: https://github.com/expr-lang/expr/blob/master/docgen/README.md Use this snippet to generate documentation in JSON format. Ensure you replace 'env' with your actual types. Run the Go program to print the JSON output. ```go package main import ( "encoding/json" "fmt" "github.com/expr-lang/expr/docgen" ) func main() { // TODO: Replace env with your own types. doc := docgen.CreateDoc(env) buf, err := json.MarshalIndent(doc, "", " ") if err != nil { panic(err) } fmt.Println(string(buf)) } ``` -------------------------------- ### Compile and Run a Simple Expression Source: https://github.com/expr-lang/expr/blob/master/docs/getting-started.md Compile a basic arithmetic expression and run it. Compiled programs can be reused for performance. ```go program, err := expr.Compile(`2 + 2`) if err != nil { panic(err) } output, err := expr.Run(program, nil) if err != nil { panic(err) } fmt.Print(output) // 4 ``` -------------------------------- ### Eval: Compile and Run in One Step Source: https://github.com/expr-lang/expr/blob/master/docs/getting-started.md Use expr.Eval for simple, one-off expressions where compiling and running can be combined. Requires an environment if the expression uses variables. ```go output, err := expr.Eval(`2 + 2`, env) ``` -------------------------------- ### Basic Aggregation Functions Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Demonstrates the use of `round`, `sum`, and `sort` functions with arrays and environment variables. ```expr round(sum($env, i)) ``` ```expr round(sum(array)) ``` ```expr sort($env ?? $env) ``` ```expr sort($env ?? add) ``` ```expr sort($env ?? array) ``` ```expr sort($env ?? f64) ``` ```expr sort($env ?? false) ``` ```expr sort($env ?? foo) ``` ```expr sort($env ?? greet) ``` ```expr sort($env ?? list) ``` ```expr sort($env ?? nil) ``` ```expr sort($env ?? ok) ``` -------------------------------- ### Get absolute value of a number Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Use `abs` to return the non-negative value of a number. ```expr abs(-5) == 5 ``` -------------------------------- ### Using Go Types and Functions in Expressions Source: https://github.com/expr-lang/expr/blob/master/docs/getting-started.md Utilize Go's built-in functions like fmt.Sprintf and slices within expressions. Ensure the function and variables are available in the environment. ```go env := map[string]any{ "greet": "Hello, %v!", "names": []string{"world", "you"}, "sprintf": fmt.Sprintf, } program, err := expr.Compile(`sprintf(greet, names[0])`, expr.Env(env)) if err != nil { panic(err) } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Print(output) // Hello, world! ``` -------------------------------- ### Object Literal Syntax Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Illustrates the creation of object literals with various key-value pairs, including handling duplicate keys and using default values. ```expr len({foo: $env ?? $env}) ``` ```expr len({foo: $env, foo: $env}) ``` ```expr len({foo: $env, foo: 0}) ``` ```expr len({foo: $env, foo: 1.0}) ``` ```expr len({foo: $env, foo: true}) ``` ```expr len({foo: $env}) ``` ```expr len({foo: 0, foo: nil}) ``` ```expr len({foo: 0, foo: str, foo: str}) ``` ```expr len({foo: 0}) ``` ```expr len({foo: 1, foo: false}) ``` ```expr len({foo: 1, foo: nil}) ``` ```expr len({foo: 1.0, foo: f64}) ``` ```expr len({foo: 1.0}) ``` ```expr len({foo: 1}) ``` ```expr len({foo: add}) ``` ```expr len({foo: array, foo: 1.0}) ``` ```expr len({foo: array, foo: greet}) ``` ```expr len({foo: array, foo: str}) ``` ```expr len({foo: array}) ``` ```expr len({foo: f64}) ``` ```expr len({foo: false}) ``` ```expr len({foo: foo, foo: $env}) ``` ```expr len({foo: foo, foo: 1.0}) ``` ```expr len({foo: foo, foo: foo}) ``` ```expr len({foo: foo, foo: nil}) ``` ```expr len({foo: foo, foo: ok}) ``` ```expr len({foo: foo}) ``` ```expr len({foo: greet, foo: str}) ``` ```expr len({foo: greet}) ``` ```expr len({foo: i, foo: $env}) ``` ```expr len({foo: i}) ``` ```expr len({foo: list, foo: foo}) ``` ```expr len({foo: list}) ``` ```expr len({foo: nil, foo: 1.0}) ``` ```expr len({foo: nil, foo: add}) ``` ```expr len({foo: nil, foo: array}) ``` ```expr len({foo: nil}) ``` ```expr len({foo: ok, foo: $env}) ``` ```expr len({foo: ok}) ``` ```expr len({foo: str, foo: $env}) ``` ```expr len({foo: str, foo: f64, foo: f64}) ``` ```expr len({foo: str, foo: greet}) ``` ```expr len({foo: str, foo: str}) ``` ```expr len({foo: str}) ``` ```expr len({foo: true}) ``` -------------------------------- ### Compile Expression with Struct Environment Source: https://github.com/expr-lang/expr/blob/master/docs/environment.md Compile an Expr expression using a struct as the environment. Expr uses reflection to discover fields and methods. ```go program, err := expr.Compile(code, expr.Env(Env{})) ``` -------------------------------- ### Get Last Element of Array Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Returns the last element from an array. Returns `nil` if the array is empty. ```expr last([1, 2, 3]) == 3 ``` -------------------------------- ### Array Literals Source: https://github.com/expr-lang/expr/blob/master/testdata/generated.txt Demonstrates creating arrays with literal values. ```expr sort([$env]) ``` ```expr sort([0 .. 0]) ``` ```expr sort([0]) ``` ```expr sort([1 ?? 0]) ``` ```expr sort([1.0]) ``` ```expr sort([1]) ``` ```expr sort([add]) ``` ```expr sort([array]) ``` ```expr sort([f64]) ``` ```expr sort([false]) ``` ```expr sort([foo]) ``` ```expr sort([greet]) ``` ```expr sort([i]) ``` -------------------------------- ### Get timezone object Source: https://github.com/expr-lang/expr/blob/master/docs/language-definition.md Use `timezone` to obtain a timezone object from a string identifier. This is useful for date conversions. ```expr timezone("Europe/Zurich") ``` ```expr timezone("UTC") ``` -------------------------------- ### Implement Visitor for Patching Source: https://github.com/expr-lang/expr/blob/master/docs/patch.md Defines a visitor that replaces occurrences of the identifier 'foo' with an integer node. ```go type FooPatcher struct{} func (FooPatcher) Visit(node *ast.Node) { if n, ok := (*node).(*ast.IdentifierNode); ok && n.Value == "foo" { // highlight-next-line ast.Patch(node, &ast.IntegerNode{Value: 42}) } } ```