The main occasions when a lambda would be preferred over a conventional DEF FN or DEF PROC are as follows:
- The function is used only once (often as an argument to a higher-order function).
- Naming the function would be unnecessary clutter (it's clearer to define it inline).
- The logic is simple enough that a full DEF would be overkill.
Suppose that we want to write a general-purpose procedure which will perform some specified (but not predetermined) operation on each element of a numeric array. We might do that as follows, where the parameter f%% is a function pointer:
Code: Select all
DEF PROCapplyToNumbers(f%%, a()) LOCAL I%
FOR I% = 0 TO DIM(a(),1) : a(I%) = FN(f%%)(a(I%)) : NEXT
ENDPROC
Code: Select all
PROCapplyToNumbers(^FNdouble(), array_of_numbers())
DEF FNdouble(x) = x * 2
could use a lambda as follows:
Code: Select all
PROCapplyToNumbers(FN_lambda("(x) = x * 2"), array_of_numbers())
Code: Select all
double = FN_lambda("(x) = x * 2")
PROCapplyToNumbers(double, array_of_numbers())
The 'magic' that makes all this happen is in this function, which could usefully be hived off into a library. If you want a challenge, figure out how it works!
Code: Select all
DEF FN_lambda(f$) : LOCAL I%, a%%, v%%, v$
FOR I% = 1 TO LENf$ : v$ += CHR$(ASCMID$(f$,I%) MOD 28 + &5F) : NEXT
v%% = EVAL("^" + v$ + "@%%") : IF ]v%% = FALSE DIM ]v%% LENf$ + 8
IF INKEY(-256)<>&57 IF @platform% AND &40 a%% = ]332 ELSE a%% = !332
]]v%% = ]v%% + 8 : IF EVAL("1RECTANGLE:" + f$) $]]v%% = $(a%% + 3)
= ]v%%