In Scheme, how do you use lambda to create a recursive function?

后端 未结 8 1012
走了就别回头了
走了就别回头了 2020-12-03 01:17

I\'m in a Scheme class and I was curious about writing a recursive function without using define. The main problem, of course, is that you cannot call a function within itse

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 01:35

    I found this question because I needed a recursive helper function inside a macro, where one can't use define.

    One wants to understand (lambda (x) (x x)) and the Y-combinator, but named let gets the job done without scaring off tourists:

     ((lambda (n)
       (let sub ((i n) (z 1))
         (if (zero? i)
             z
             (sub (- i 1) (* z i)) )))
     5 )
    

    One can also put off understanding (lambda (x) (x x)) and the Y-combinator, if code like this suffices. Scheme, like Haskell and the Milky Way, harbors a massive black hole at its center. Many a formerly productive programmer gets entranced by the mathematical beauty of these black holes, and is never seen again.

提交回复
热议问题