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

后端 未结 8 980
走了就别回头了
走了就别回头了 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.

    0 讨论(0)
  • Basically what you have is a form similar to the Y combinator. If you refactored out the factorial specific code so that any recursive function could be implemented, then the remaining code would be the Y combinator.

    I have gone through these steps myself for better understanding.
    https://gist.github.com/z5h/238891

    If you don't like what I've written, just do some googleing for Y Combinator (the function).

    0 讨论(0)
提交回复
热议问题