tags:

views:

354

answers:

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

I wrote this function, but how would I express this more clearly, using simple recursion with repeated?

I'm sorry, I forgot to define my compose function.

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

And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.

A: 

What is your function trying to do, just out of curiosity? Is it to run f, n times? If so, you can do this.

(define (repeated f n)
  (for-each (lambda (i) (f)) (iota n)))
Chris Jester-Young
+1  A: 

I'm assuming that (repeated f 3) should return a function g(x)=f(f(f(x))). If that's not what you want, please clarify. Anyways, that definition of repeated 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)))
Kyle Cronin
+1  A: 
(define (repeated f n)
  (lambda (x)
    (let recur ((x x) (n n))
      (if (= n 0)
          args
          (recur (f x) (sub1 n))))))

Write the function the way you normally would, except that the arguments are passed in two stages. It might be even clearer to define repeated this way:

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

You don't have to use a 'let-loop' this way, and the lambdas make it obvious that you expect your arguments in two stages. (Note:recur is not built in to Scheme as it is in Clojure, I just like the name)

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

The cool functional feature you want here is currying, not composition. Here's the Haskell with implicit currying:

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

I hope this isn't a homework problem.

Nathan Sanders