| 419 | } |
| 420 | |
| 421 | func ExampleOperator_with_decimal() { |
| 422 | type Decimal struct{ N float64 } |
| 423 | code := `A + B - C` |
| 424 | |
| 425 | type Env struct { |
| 426 | A, B, C Decimal |
| 427 | Sub func(a, b Decimal) Decimal |
| 428 | Add func(a, b Decimal) Decimal |
| 429 | } |
| 430 | |
| 431 | options := []expr.Option{ |
| 432 | expr.Env(Env{}), |
| 433 | expr.Operator("+", "Add"), |
| 434 | expr.Operator("-", "Sub"), |
| 435 | } |
| 436 | |
| 437 | program, err := expr.Compile(code, options...) |
| 438 | if err != nil { |
| 439 | fmt.Printf("Compile error: %v", err) |
| 440 | return |
| 441 | } |
| 442 | |
| 443 | env := Env{ |
| 444 | A: Decimal{3}, |
| 445 | B: Decimal{2}, |
| 446 | C: Decimal{1}, |
| 447 | Sub: func(a, b Decimal) Decimal { return Decimal{a.N - b.N} }, |
| 448 | Add: func(a, b Decimal) Decimal { return Decimal{a.N + b.N} }, |
| 449 | } |
| 450 | |
| 451 | output, err := expr.Run(program, env) |
| 452 | if err != nil { |
| 453 | fmt.Printf("%v", err) |
| 454 | return |
| 455 | } |
| 456 | |
| 457 | fmt.Printf("%v", output) |
| 458 | |
| 459 | // Output: {4} |
| 460 | } |
| 461 | |
| 462 | func fib(n int) int { |
| 463 | if n <= 1 { |