Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

n-ary function in scheme

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?

like image 223
padawanMiyagi Avatar asked Jun 04 '26 01:06

padawanMiyagi


1 Answers

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
like image 156
Sylwester Avatar answered Jun 08 '26 00:06

Sylwester