Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When most people think of <em>functions</em>, they think of <strong>named functions</strong>:</p> <pre><code>function foo() { return "This string is returned from the 'foo' function"; } </code></pre> <p>These are called by name, of course:</p> <pre><code>foo(); //returns the string above </code></pre> <p>With <em>lambda expressions</em>, you can have <strong>anonymous functions</strong>:</p> <pre><code> @foo = lambda() {return "This is returned from a function without a name";} </code></pre> <p>With the above example, you can call the lambda through the variable it was assigned to:</p> <pre><code>foo(); </code></pre> <p>More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:</p> <pre><code>function filter(list, predicate) { @filteredList = []; for-each (@x in list) if (predicate(x)) filteredList.add(x); return filteredList; } //filter for even numbers filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); </code></pre> <p>A <em>closure</em> may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:</p> <pre><code>@x = 0; function incrementX() { x = x + 1;} incrementX(); // x now equals 1 </code></pre> <p>That doesn't seem like much but what if this was all in another function and you passed <code>incrementX</code> to an external function?</p> <pre><code>function foo() { @x = 0; function incrementX() { x = x + 1; return x; } return incrementX; } @y = foo(); // y = closure of incrementX over foo.x y(); //returns 1 (y.x == 0 + 1) y(); //returns 2 (y.x == 1 + 1) </code></pre> <p>This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:</p> <pre><code>function foo() { @x = 0; return lambda() { x = x + 1; return x; }; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload