Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can a lambda call itself? #60

Open
bouk opened this issue Mar 24, 2019 · 2 comments
Open

How can a lambda call itself? #60

bouk opened this issue Mar 24, 2019 · 2 comments

Comments

@bouk
Copy link

bouk commented Mar 24, 2019

I'm trying to create a function that returns a function that calls itself. I tried this:

(define (multo ex) (let ((f (lambda (n) (if
                        (= 0 n)
                        1
                        (* ex (f (- n 1))))))) f))
(println "~s" ((multo 3) 3))

But it doesn't work because the lambda can't refer to f inside the definition. How do I achieve this?

@murarth
Copy link
Owner

murarth commented Mar 24, 2019

I don't believe this was previously possible, so I've implemented the call-self operator, which provides a clear and straightforward method to recurse within a lambda.

The above code can now be written as:

(define (multo ex) (lambda (n) (if (= 0 n) 1 (* ex (call-self (- n 1))))))

Also, I've just published this as part of version 0.11.0 on crates.io.

@eaglgenes101
Copy link

eaglgenes101 commented Mar 26, 2019

In other lisps, this would be handled by creating a letrec binding to a lambda which calls on its own binding. No real need for the ability to specifically have a way to refer to self (but it can be done, if you are sufficiently inclined, given the general malleability of the family of lisps).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants