How can I more clearly express this function of the Scheme?

(define (repeated f n)
   if (= n 0)
   f
   ((compose repeated f) (lambda (x) (- n 1))))

I wrote this function, but how could I express it more clearly using simple recursion with repetition?

Sorry, I forgot to define my layout function.

(define (compose f g) (lambda (x) (f (g x))))

And the function takes as inputs a procedure that calculates f and a positive integer n, and returns a procedure that calculates the nth reapplication of f.

+3
source share
3 answers

I assume that (repetition of f 3) should return the function g (x) = f (f (f (f (x))). If this is not what you want, please clarify. In any case, this definition of repetition can be written as follows:

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

(define (square x)
  (* x x))

(define y (repeated square 3))

(y 2) ; returns 256, which is (square (square (square 2)))
+1
source
(define (repeated f n)
  (lambda (x)
    (let recur ((x x) (n n))
      (if (= n 0)
          args
          (recur (f x) (sub1 n))))))

, , , . repeated :

(define repeated (lambda (f n) (lambda (x) 
  (define (recur x n)
    (if (= n 0)
        x
        (recur (f x) (sub1 n))))
  (recur x n))))

"let-loop" , lambdas , . (: recur Scheme, Clojure, )

> (define foonly (repeat sub1 10))
> (foonly 11)
1
> (foonly 9)
-1

, , - , . Haskell :

repeated _ 0 x = x
repeated f n x = repeated f (pred n) (f x)

, .

+1

What function are you trying to do, just out of curiosity? Is it running f, ntime? If so, you can do it.

(define (repeated f n)
  (for-each (lambda (i) (f)) (iota n)))
0
source

Source: https://habr.com/ru/post/1699339/


All Articles