I was going through Structure and interpretation of computer programming by Brain harvey. I came across this question which i could not figure out how to do it.
How do we write recursive procedure with lambda in Scheme?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
TL;DR: Use named
let(if you are executing a recursive function immediately) orrec(if you are saving the recursive function for later execution).The usual way is with
letrec, or something that uses aletrecbehind the scenes, like namedletorrec. Here’s a version of(factorial 10)usingletrec:And the same thing using named
let:The key understanding here is that both versions are exactly the same. A named
letis just a macro that expands to theletrecform. So because the namedletversion is shorter, that is usually the preferred way to write a recursive function.Now, you might ask, what if you want to return the recursive function object directly, rather than execute it? There, too, you can use
letrec:There, too, is a shorthand for this, although not using named
let, but instead usingrec:The nice thing about using
rechere is that you can assign the function object to a variable and execute it later.The more theoretical and “pure” way to create recursive functions is to use a Y combinator. 🙂 But most practical Scheme programs do not use this approach, so I won’t discuss it further.