Function literals

From D Wiki
Revision as of 20:57, 23 November 2012 by Shd (talk | contribs) (literals)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Function Literals enable embedding anonymous functions directly into expressions.

For example:

  int function(char c) fp;
  void main()
  {
    static int foo(char c) { return 6; }
    fp = &foo;
  }


is exactly equivalent to:

  int function(char c) fp;
  void main()
  {
    fp = function int(char c) { return 6;}; //note the semi-colon at the end
  }


We now have anonymous functions...


This has brought up the specter of /DynamicClosures. The nested and/or anonymous functions can only access dynamic scope, which means scope that exists on the stack at the time of execution. This differs from lexical scope, which refers to the scope as indicated by the program text structure.

(More information can be found in the D Spec: Closures and Function Literals.)