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

后端 未结 16 2154
一整个雨季
一整个雨季 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 05:57

    Clojure can do it, as fn takes an optional name specifically for this purpose (the name doesn't escape the definition scope):

    > (def fac (fn self [n] (if (< n 2) 1 (* n (self (dec n))))))
    #'sandbox17083/fac
    > (fac 5)
    120
    > self
    java.lang.RuntimeException: Unable to resolve symbol: self in this context
    

    If it happens to be tail recursion, then recur is a much more efficient method:

    > (def fac (fn [n] (loop [count n result 1]
                         (if (zero? count)
                           result
                           (recur (dec count) (* result count))))))
    

提交回复
热议问题