Reputation: 116
I am in the middle of writing an assignment for my CS class in scheme. I have to write a n-ary function based on another function called chili, which takes 3 arguments and a operator as input and returns the variables combined with the operators, like so:
> ((((Chili3 +) 1) 10) 100)
111
And the code:
(define Chili3
(lambda (p)
(lambda (x1)
(lambda (x2)
(lambda (x3)
(p x1 x2 x3))))))
The funtion that i am supposed to write has to take another input, that defines the number of arguments that the function will use and will be excecuted like so:
> ((((((Curry 5 *) 1) 2) 3) 4) 5)
120
Here is the code that i have so far:
(define Chili
(lambda (n p)
(lambda(xs)
((p n) xs))))
Can anbody help me, maybe just explaining how the n-ary functions work, or what is wrong with the code that i have?
Upvotes: 3
Views: 341
Reputation: 48775
Here is my take on it.
(define (curry-n n proc)
(let curry-n-aux ((n n) (args '()))
(if (zero? n)
(apply proc (reverse args))
(lambda (x)
(curry-n-aux (- n 1) (cons x args))))))
(curry-n 0 (lambda () "hello")) ; ==> "hello"
((curry-n 1 values) "hello") ; ==> "hello"
((((((curry-n 5 *) 1) 2) 3) 4) 5); ==> 120
A different approach would be to have a special "apply" value that applies:
(define %curry-apply (list 'apply))
(define (curry proc)
(let curry-n-aux ((args '()))
(lambda (x)
(if (eq? x %curry-apply)
(apply proc (reverse args))
(curry-n-aux (cons x args))))))
((curry-n (lambda () "hello")) %curry-apply) ; ==> "hello"
(((curry-n values) "hello") %curry-apply) ; ==> "hello"
(((((((curry-n *) 1) 2) 3) 4) 5) %curry-apply); ==> 120
Upvotes: 2
Reputation: 31145
Here is a simple function that takes an arbitrary number of arguments. The dot signals that it is an n-ary function.
(define (plus . xs)
(define n (length xs))
(display "The number of arguments were: ")
(display n)
(newline)
(apply + xs))
(plus)
(plus 1)
(plus 1 2)
(plus 1 2 3)
Upvotes: 1