N-ary function in the circuit

I am in the middle of writing an assignment for my CS class in a schema. I have to write an n-ary function based on another chili function that takes 3 arguments and an operator as input and returns variables combined with operators:

> ((((Chili3 +) 1) 10) 100)
111

      

And the code:

(define Chili3
  (lambda (p)
    (lambda (x1)
      (lambda (x2)
        (lambda (x3)
          (p x1 x2 x3))))))

      

The funtion function I have to write has to take another input that determines the number of arguments the function will use and will be excluded like so:

> ((((((Curry 5 *) 1) 2) 3) 4) 5)
120

      

Here is the code I have so far:

(define Chili
  (lambda (n p)
    (lambda(xs)
    ((p n) xs))))

      

Can anyone help me, maybe just explain how n-ary functions work or what is wrong with the code I have?

+3


source to share


2 answers


Here's my example.

(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

      



Another approach would be to apply the special meaning "apply":

(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

      

+2


source


Here's a simple function that takes an arbitrary number of arguments. The dot signals that this 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)

      

+1


source







All Articles