2814

27
+7  Q:

## Rosetta Stone: Lambda expressions

How are anonymous functions/lambda expressions expressed in various programming languages? Are the syntax and semantics especially useful or not useful in that language? Are there any programming languages for which true anonymous functions aren't possible?

Like other Rosetta Stone questions, responses should start with the name of the language being demonstrated, and the demo should (hopefully) be interesting to people seeking new languages to learn.

+4  A:

LISP (Common Lisp/Scheme):

``````(lambda (y) (* y 2))
``````

JavaScript:

``````x = function(y) { return 2*y; };
``````

Python:

``````lambda x: 2*x
``````

PHP (>= 5.3):

``````\$x = function(y) { return 2 * y; };
``````
+3  A:

Perl:

``````\$f = sub { 2 * \$_[0] };
``````
+5  A:

``````\x -> 2 * x
``````
Although not a lambda (but rather partial function application), the following would also work in this example: (2*)
+2  A:

Lua:

``````f = function (x) return 2 * x end
``````
By far the most readable example out of all of this, +1!
+1  A:

Ocaml:

``````fun x -> 2 * x
``````
+1  A:

Javascript

``````var f = function(x){ return x*2;};
f(3);
``````

PHP

``````\$f = create_function('\$x', 'return \$x*2;');
\$f(3);
``````

Python

``````f = lambda x: x*2
f(3)
``````

It is worth noting that Python lambdas can only be expressions, not a sequence of arbitrary statements as a regular function can.

SML

``````val f = fn x=>x*2;
f(3);
``````
I didn't see the first example when writing this (although our example functions are identical)
A:

erlang:

``````fun(X) -> 2 * X end
``````
+6  A:

C# 3.0:

``````var f = x => 2 * x;
``````
+3  A:

Ruby:

``````lambda {|x| x * 2}
``````

or

``````Proc.new {|x| x * 2}
``````
You might want to make a note that a Proc.new call to return will return from the calling method.
-or- proc{|x|x*2}
+4  A:

Mathematica:

``````2*#&
``````

The #, #2, etc are the arguments and ampersand makes everything previous be the lambda function (use parens if that's ambiguous). You can also use ## for, essentially, the list of all the arguments.

The above is syntactic sugar for

``````Function[x, 2*x]
``````

Also, the `*` is optional, making Mathematica, I reckon, the winner by character count:

``````2#&
``````
+10  A:

Java:

``````public interface Lambda<A,V> {

V call(A a);

}

public class LambdaTest extends Object {

public static void main(String argv[]) {

Lambda<String, Integer> lambda=new Lambda<String, Integer>() {
public Integer call(String s) {
return Integer.parseInt(s);
}
};

System.out.printf("Got %d\n", lambda.call(argv[0]));

}

}
``````
I almost want to mark this "offensive" but that wouldn't be nice. :)
Heh. It is a little offensive... my intentions were mostly good, though. :)
No offense, but Java's lambdas look like a horrible kludge grafted onto a function.
+1: Funny because its true
A:

Reverse Polish Lisp (my first highlevel programming language):

``````<< 2 * >>
``````

edit

I should point out that the same in factor looks like this:

``````[ 2 * ]
``````
+2  A:

Arc:

``````[* 2 _]
``````
+1  A:

VB

Dim a = Function(x) x * 2

+2  A:

MATLAB:

``````f = @(x) x^2;
g = @(k) @(x) x+k;
g3 = g(3);
% g is a function that returns a function
``````
+2  A:

Scala:

``````(x => 2 * x)
``````
+2  A:

## `Perl 6`

As always with Perl, TMTOWTDI (There is more than one way to do it).

``````my \$square_pointy  =  ->  \$num {  \$num ** 2 };
my \$square_block   =           {    \$_ ** 2 };
my \$square_block_n =           { \$^num ** 2 };
my \$square_sub     = sub (\$num){  \$num ** 2 };

say \$square_pointy(4);
say \$square_block(4);
say \$square_block_n(4);
say \$square_sub(4);
``````
+1  A:

There are actually two ways to do this in JavaScript, although so far I've only seen this one mentioned:

``````var f = function(x){ return x*2;};
``````

As of JavaScript 1.8, you can do this:

``````var f = function(x) x * 2;
``````
+3  A:

F#:

``````fun x -> x * x
``````
i thought it was `let myFun x = x * x`
@RCIX: Lambda expression = anonymous function definition; `let myFun x = x * x` creates a function with name `myFun` whereas `fun x -> x * x` creates a function without a name.
+3  A:

C++

``````#include <boost/lambda.hpp>

using namespace boost::lambda;

boost::function<int (int)> f = (_1 * 2);
``````
+4  A:

`\x y -> x * y`

or `\x -> x *`

or `(x *)`

Almost all descendants of Lisp and ISWIM (ML, Haskell, etc.) support some kind of terse syntax for lambda expressions. The latter family also generally allows automatic currying, which means that instead of writing `x => (y => f(x, y))` you can write `f(x,)` and the language will automatically interpret this as a sort of lambda expression.

In some languages this even extends to binary operators. In Haskell, for example, `(* 2)` is a valid (and commonplace) expression for an anonymous function that multiplies its argument by two.

Historically, descendants of Algol and Fortran (including the entire C and Pascal family) have not supported any kind of lambda expression until very recently. Languages with some degree of OOP support (including C++ and Java) allow you to write "functor objects," but that's usually much more verbose and a bit less flexible than "real" lambda expressions.

+3  A:

Smalltalk:

The definition ....

``` [:x | x * 2] ```

The evaluation ....

``` [:x | x * 2] value: 4 ```

+4  A:

C++0x:

``````auto f = [](int x){ return x*2; }; // Definition
std::cout << f(3);                 // Usage
``````

A:

ActionScript 3.0

``````var stringFilter:Function = function(input:String):String { return input.toUpperCase(); };

var multiplyer:Function = function(x:Number):Number { return x * 2.0; };
``````

Similar to Javascript, but more type-safe.

A:

J

This doesn't really use lambdas, but it's an anonymous function at least.

``````2&*
``````

Demonstration:

``````    (2&*) 6
12
(2&*) 3 4 5
6 8 10
``````
+1  A:

## Tcl (8.5+)

``````# Create a lambda term; note there's no particularly special syntax here
set mulBy2 [list x {expr {\$x * 2}}]

# Use it; [apply] is synthesizable in 8.4 and before, but very costly
apply \$mulBy2 21
``````

Note that it's advisable if doing this to use command prefixes and expansion for application:

``````set mul2 [list ::apply [list x {expr {\$x * 2}}]]
{*}\$mul2 21
``````

This is preferable as it allows other ways to express the same thing, for example:

``````set mul2 [list ::tcl::mathop::* 2]
``````
A:

Does this count as lambda for C/C++ ?

`#include <stdlib.h>`
`#include <stdio.h>`
`#define lambda(x) (x*2)`
```float x(float x) { return x+20; }```
```int main() { float v=1; printf("%f",lambda(x(v))); }```