SICP 习题 (1.43)解题总结

SICP 习题 1.43 是前面两道题的延续,习题要求我们定义一个过程(repeat f n) 。当中f是一个单參数过程。题目要求我们通过repeat过程将过程f调用n次,注意是嵌套调用n次,不是连续调用n次。就是说结果应该是(f ( f ( … (f x) …)))。而不是(begin (f x) (f x) (f x) … (f x))。


题目还提醒我们使用习题1.42所定义的compose方法。


细致想想的话这一工作能够通过递归调用完毕,就是(repeat f n) 等于 (compose f (repeat f (- n 1))。就是说n次嵌套调用f能够转换成(f (<n-1次嵌套调用f))。


理解了这一点后就比較easy了,控制好递归调用的结束就能够了。代码例如以下:


(define (repeat f n)
  (define (repeat-inner f cur-n)
    (if (< cur-n n)
	 (compose f (repeat-inner f (+ cur-n 1)))
	f ))
  (repeat-inner f 1))



猜你喜欢

转载自www.cnblogs.com/mqxnongmin/p/10770104.html