Calculation of function n times in the circuit

I am having trouble deciding how to execute a function a certain number of times. That is, I provide the function with a natural number n and the function fun, and it executes the function n times. For instance:

(curry n fun) 

Is the function and the possible application:

 (((((curry 4 +) 1) 2) 3) 4) 

To produce 10.

I'm really not sure how to implement it correctly. Can someone please give me a hand? Thanks:)

+3
source share
2 answers

You can write your own n-curry procedure by retyping curry :

 (define (n-curry n func) (let loop ([i 1] [acc func]) (if (= in) acc (loop (add1 i) (curry acc))))) 

If you are in Racket, it can be expressed a little easier with a for/fold iteration:

 (define (n-curry n func) (for/fold ([acc func]) ([i (in-range (sub1 n))]) (curry acc))) 

In any case, use it like this:

 (((((n-curry 4 +) 1) 2) 3) 4) => 10 
+2
source
 ;;; no curry ;;; (Int, Int, Int) => Int (define sum (lambda (xyz) (+ xyz) ) ) (sum 1 2 3) ;;; curry once ;;; (Int) => ((Int x Int) => Int) (define sum (lambda (x) (lambda (yz) (+ xyz) ) ) ) (define sum+10 (sum 10)) (sum+10 10 20) ;;; curry 2 times ;;; (Int) => (Int => (Int => Int) ) (define sum (lambda (x) (lambda (y) (lambda (z) (+ xyz) ) ) ) ) (define sum+10+20 ((sum 10) 20)) (sum+10+20 30) 

;;; Now we summarize, based on these examples:

 (define (curry nf) (if (= n 0) (lambda (x) x) (lambda (x) (f ((curry (- n 1) f) x))))) 

;;; Example: apply function 1+ 11 times to the initial number 10, results 21:

 ((curry 11 (lambda (x) (+ x 1))) 10) 
+2
source

All Articles