Which languages support *recursive* function literals / anonymous functions?

Posted by Hugh Allen on Stack Overflow See other posts from Stack Overflow or by Hugh Allen
Published on 2008-10-01T05:46:48Z Indexed on 2010/05/20 1:20 UTC
Read the original article Hit count: 336

It seems quite a few mainstream languages support function literals these days. They are also called anonymous functions, but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, &printf doesn't count.

EDIT to add: if you have a genuine function literal expression <exp>, you should be able to pass it to a function f(<exp>) or immediately apply it to an argument, ie. <exp>(5).

I'm curious which languages let you write function literals which are recursive. Wikipedia's "anonymous recursion" article doesn't give any programming examples.

Let's use the recursive factorial function as the example.

Here are the ones I know:

  • JavaScript / ECMAScript can do it with callee:

    function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}}
    
  • it's easy in languages with letrec, eg Haskell (which calls it let):

    let fac x = if x<2 then 1 else fac (x-1) * x in fac

    and there are equivalents in Lisp and Scheme. Note that the binding of fac is local to the expression, so the whole expression is in fact an anonymous function.

Are there any others?

© Stack Overflow or respective owner

Related posts about language-features

Related posts about recursion