Skip to content

Instantly share code, notes, and snippets.

@lojic
Last active November 3, 2015 17:04
Show Gist options
  • Save lojic/9679cf28dae15ca051d0 to your computer and use it in GitHub Desktop.
Save lojic/9679cf28dae15ca051d0 to your computer and use it in GitHub Desktop.
#lang racket
(define (memoize proc)
(define memo '())
(λ (x)
(cond [(assq x memo) => cdr]
[else (let ([result (proc x)])
(set! memo (cons (cons x result) memo))
result)])))
(define fibonacci
(memoize
(λ (n)
(if (< n 2)
1
(+ (fibonacci (- n 1))
(fibonacci (- n 2)))))))
(fibonacci 100) ; => 573147844013817084101
(define (memoize proc)
(define memo '())
(λ x
(cond [(assq x memo) => cdr]
[else (let ([result (apply proc x)])
(set! memo (cons (cons x result) memo))
result)])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment