Comparing Lambda Syntax

Posted on March 20, 2021

How do you syntactially represent an unnamed, inline, expression for a function? Alonzo Church chose λx.M (where x is the argument and M is the body of the function) when he designed the lambda calculus in the 1930s, as a way of formalizing the idea of “computation” before we had computers. Mathematicians also use the syntax x → M to represent a function from the value x to the expression M. Both of these are rarely used in programming languages, for one reason: while the lambda and the arrow are valid unicode characters these days, they’re still a pain to type on the standard keyboard.

The rest of this blog post is merely a comparison of various lambda syntaxes in popular programming languages, purely for reference. I will probably edit this post often in order to add more languages as I find them.

Languages which use “lambda” spelled out

  • Lisp: (lambda (x) (+ x 1))
  • Python: lambda x: x + 1

Languages which use some other representation of a lambda

  • Haskell: \x -> x + 1 (also uses -> as the representation of an arrow)

Languages which use an ascii arrow

  • JavaScript: x => x + 1
  • Java: x -> x + 1
  • Haskell: \x -> x + 1 (also uses \ as the representation of a lambda)
  • C#: x => x + 1
  • Swift: { (x: Int) -> Int in x + 1 }
  • OCaml: fun (x : int) -> x + 1 (also uses fun as an abbreviation for “function”)

Languages which use some variant of the word “function”

  • JavaScript: function(x){ return x+1; }
  • Go: func(i int){ return i + 1; }
  • R: function(x) x + 1
  • PHP: function($x) { return $x + 1 }
  • OCaml: fun (x : int) -> x + 1 (also uses -> as the representation of an arrow)

Languages which use some other syntax

  • Rust: |x| x + 1
  • Ruby: |x| x + 1
  • Ruby: ->(x) { x + 1 }
  • C++: `{ return x + 1; }