Lambdas in BBC BASIC

The question was recently asked: "Does BBC BASIC have lambdas?" (i.e. anonymous functions). The 'official' answer is no, in the sense that the language itself does not incorporate that concept, but as is so often the case the functionality can quite easily be synthesised from lower-level operations.

Here is an example (it relies on extensions available in BBC BASIC for Windows, BBC BASIC for SDL 2.0 and the Console Mode editions):
      PROC_lambda(foo{}, "(x) = x * x")
      PROC_lambda(bar{}, "(x) PRINT x ^ 2 : ENDPROC")
      PRINT FN(foo{})(5)

      DEF PROC_lambda(RETURN a{}, a$)
      LOCAL a%% : DIM a{a%%, a$}
      IF INKEY(-256) <> &57 IF @platform% AND &40 a%% = ]332 ELSE a%% = !332
      IF EVAL("1RECTANGLE:" + a$) a$ = $(a%% + 3)
      a.a$ = a$ + CHR$&D : a.a%% = PTR(a.a$)

Here we create two lambdas, foo (which is function-like) and bar (which is procedure-like); these are captured as opaque structures, because that's the data type most suited to holding a lambda. They are then executed using the normal syntax for an indirect function or procedure call.

If the lambda doesn't take any parameters, simply omit the initial parenthesised list. As shown this code can only accept single-line lambdas, but it would be possible to extend it to multi-line functions using a suitable syntax to indicate the line delimiter.
Sign In or Register to comment.