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

后端 未结 16 2101
一整个雨季
一整个雨季 2021-02-04 05:09

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 th

16条回答
  •  鱼传尺愫
    2021-02-04 06:06

    'Tseems you've got the idea of anonymous functions wrong, it's not just about runtime creation, it's also about scope. Consider this Scheme macro:

    (define-syntax lambdarec
      (syntax-rules ()
        ((lambdarec (tag . params) . body)
         ((lambda ()
           (define (tag . params) . body)
            tag)))))
    

    Such that:

    (lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1)))))
    

    Evaluates to a true anonymous recursive factorial function that can for instance be used like:

    (let ;no letrec used
        ((factorial (lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1)))))))
      (factorial 4)) ; ===> 24
    

    However, the true reason that makes it anonymous is that if I do:

    ((lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1))))) 4)
    

    The function is afterwards cleared from memory and has no scope, thus after this:

    (f 4)
    

    Will either signal an error, or will be bound to whatever f was bound to before.

    In Haskell, an ad hoc way to achieve same would be:

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

    The difference again being that this function has no scope, if I don't use it, with Haskell being Lazy the effect is the same as an empty line of code, it is truly literal as it has the same effect as the C code:

    3;
    

    A literal number. And even if I use it immediately afterwards it will go away. This is what literal functions are about, not creation at runtime per se.

提交回复
热议问题