Racket week1 Avoiding Unnecessary Computations

(define (slow-add x y)
    (letrec ([slow-id (lambda (y z)
                        (if (= z 0)
                            y
                            (slow-id y (- z 1))))])
        (+ (slow-id y 500000) x)
    )
)



(define (my-mult x y-thunk)
    (cond [(= x 0) 0]
          [(= x 1) (y-thunk)]
          [#t (+ (y-thunk) (my-mult (- x 1) y-thunk))]
    )
)


(my-mult 0 (lambda () (slow-add 3 4)))
(my-mult 1 (lambda () (slow-add 3 4)))
(my-mult 20 (lambda () (slow-add 3 4))) ;;calculate thunk for 20times
(my-mult 20 (let ([x (slow-add 3 4)]) (lambda () x)))

What if we could take some computation that always return the same result, had no side effects, didn't matter when it was executed, and we did not compute it until we needed it?

But then, once we did need it we remembered the answer, so in the future we, didn't have to compute it again. We would just return that remembered result immediately.

Well, this has a name, it's called lazy evaluation,

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,449评论 0 23
  • 我在过去你在未来 /令狐小聪 未来的未来必将会来 过去的过去永远不会过去 一悲成佛 一怒成魔 恩怨散在一笑间 莲花...
    令狐小聪阅读 1,813评论 0 0
  • July 9,2013 我和《玩的就是心跳》第一次邂逅 平实通俗苦心堆砌的文字填充在全篇的一字字,一段段,一页页,...
    Martinzz阅读 3,764评论 0 0
  • 低沉的耳语 淹没在嘈杂里 残留的氧气 消散在气泡里 泛起的涟漪 折射着太阳的气息 压迫的重力 快要无法呼吸 变形的...
    sincillin阅读 2,875评论 0 1
  • 从此世界再无光明 黑暗 给人模糊、给人未知 更多是恐惧 每次重生都有你的伴随 感谢一路有你陪伴 泰山、西藏、香港 ...
    赋得永久的悔阅读 916评论 0 0