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

后端 未结 8 1038
走了就别回头了
走了就别回头了 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:59

    The expression (lambda (x) (x x)) creates a function that, when evaluated with one argument (which must be a function), applies that function with itself as an argument.

    Your given expression evaluates to a function that takes one numeric argument and returns the factorial of that argument. To try it:

    (let ((factorial ((lambda (x) (x x))
                      (lambda (fact-gen)
                        (lambda (n)
                          (if (zero? n)
                              1
                              (* n ((fact-gen fact-gen) (sub1 n)))))))))
      (display (factorial 5)))
    

    There are several layers in your example, it's worthwhile to work through step by step and carefully examine what each does.

提交回复
热议问题