Scheme procedure to compute the nth repeated application of a function?

你说的曾经没有我的故事 提交于 2019-12-06 14:52:00

Well, you probably want something like this, right?

((repeated square 3) 5)
-> (square ((repeated square 2) 5))
-> (square (square ((repeated square 1) 5)))
-> (square (square (square ((repeated square 0) 5))))
-> (square (square (square (identity 5))))

(I don't know whether identity is predefined in Scheme. If not, it's easy to write.)

Now, this is not directly reproducible because you can't magically enclose code outside of the call to repeated with arbitrary stuff. However, what do these reduction steps look like when rewritten using compose? Can you make out a pattern in the resulting list of steps and reproduce it?

(define (repeated f n)
  (if (zero? n)
    identity
    (lambda (x) ((repeated f (- n 1)) (f x)))))

or, if you insist on using "compose":

(define (repeated f n)
  (if (zero? n)
    identity
    (compose (repeated f (- n 1)) f)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!