Following up from a previous question I asked about writing a curry function, How to create a make-curry function like racket has, I've started writing the fixed case for 0, 1, 2 -- they are very similar to Church Numerals which is pretty neat. Here is what I have so far:
(define (curry-0 func)
func)
(define hello (begin (display "Hello!") (newline)))
(curry-0 hello)
; Hello!
(define (curry-1 func)
(lambda (x)
(func x )))
((curry-1 -) 2)
; -2
(define (curry-2 func)
(lambda (x)
(lambda (y)
(func x y))))
(((curry-2 +) 2) 3)
5
The pattern seems to be:
(define curry-n func
(lambda (x1)
(lambda (x2)
...
(lambda (xn)
(func x1 x2 ... xn)
However, I'm having some trouble 'building up' the n-nested lambda expression. I suppose I could build a nested lambda with something like:
(define (curry-n num func)
(if (num > 0)
(lambda (?) (curry-n (- num 1) func))))
But I'm not sure how I would 'bind' the variables to each lambda function and also how I would end up passing those same variables (in order) to the (func x1 x2 ... xn) function.
This is incorrect but I've started along the lines of...
(define (curry-n num func)
(if (> num 0)
; but lambda won't accept a number, possible to string-format?
(curry-n (- num 1) (lambda (num)))))
How could this be done?
using a loop
You need some sort of
loopto collect eachargfrom thelambda-curryshould always return a procedure, so you can seeloopwill always return alambda, even for thenum = 0case. Eachargiscons'd ontoargs, creating a reversed list of arguments. This is why wereversetheargsbeforeapplying the user-supplied procedure,f.It works like this -
using delimited continuations
In the spirit of sharing learning exercises, take some time to review this example using delimited continuations -
To get
curry-nall we need to do is build a list ofncontinuations!And it works just like our first one -
You can visualize the process as working something like this, where each
__is a "hole" to fill -The only difference is there are
nholes to fill, so we build a list ofnholes andapply-scheme
I didn't notice you were doing this work in Scheme. We can define
build-list-And we can use Olivier Danvy's original implementation of shift/reset,
Our
curry-ncan stay the same -