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

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

    I like this question. 'The scheme programming language' is a good book. My idea is from Chapter 2 of that book.

    First, we know this:

    (letrec ((fact (lambda (n) (if (= n 1) 1 (* (fact (- n 1)) n))))) (fact 5))
    

    With letrec we can make functions recursively. And we see when we call (fact 5), fact is already bound to a function. If we have another function, we can call it this way (another fact 5), and now another is called binary function (my English is not good, sorry). We can define another as this:

    (let ((another (lambda (f x) .... (f x) ...))) (another fact 5))
    

    Why not we define fact this way?

    (let ((fact (lambda (f n) (if (= n 1) 1 (* n (f f (- n 1))))))) (fact fact 5))
    

    If fact is a binary function, then it can be called with a function f and integer n, in which case function f happens to be fact itself.

    If you got all the above, you could write Y combinator now, making a substitution of let with lambda.

提交回复
热议问题