Feat: Implement Lambda Functions and Callable Interface #39
+217
−34
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request introduces support for lambda functions and the underlying Callable interface that makes them possible. It closes #38. Regular functions are still fully supported, no change there.
This pull request's code should only be checked once #36 is merged, as both of them modify the
lib/src/parser.dart
and this pull request is already built on the changes introduced by #36. So looking at the code before the other pull request is merged will also show changes from the other pull request.The Callable Interface
A new abstract class,
Callable
, has been introduced to act as a formal contract for function-like objects. When evaluating a call expression, the evaluator now checks if the callee is aCallable
.This is a worthwhile addition in its own right, as it allows users to implement custom functions that can validate their arguments and throw descriptive exceptions for parameter mismatches, which was not possible with the previous
Function.apply
approach.Lambda Functions
This PR adds parser support for lambda functions using the common arrow syntax:
(p1, p2) => body_expression
.Evaluating a lambda expression now creates an internal
Callable
object that captures its defining context (lexical scope). This simple enhancement unlocks powerful new capabilities, allowing for expressive collection-based operations directly in the expression language.[1, 9, 2, 5, 3, 2].where((e) => e > 2)
[1, 2, 3].map((e) => e * 2)
While the lambda receives its own arguments, it also retains access to the context in which it was created, allowing for complex expressions that mix local parameters with external variables.
The
README.md
and tests have been updated to reflect these powerful new features. We also put the example code of theREADME.md
into appropriate code blocks to enable syntax highlighting on Github.This pull request solves #38