ketos icon indicating copy to clipboard operation
ketos copied to clipboard

How can a lambda call itself?

Open bouk opened this issue 7 years ago • 2 comments

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?

bouk avatar Mar 24 '19 11:03 bouk

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.

murarth avatar Mar 24 '19 19:03 murarth

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).

eaglgenes101 avatar Mar 26 '19 17:03 eaglgenes101