(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,