Created
September 29, 2012 22:59
-
-
Save dyoo/3805375 to your computer and use it in GitHub Desktop.
Pascal's triangle memoized
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
;; http://www.cforcoding.com/2012/01/interview-programming-problems-done.html | |
;; A little syntax for memoizing functions like Pascal's triangle. | |
(define-syntax (define/memo stx) | |
(syntax-case stx () | |
[(_ (name args ...) body ...) | |
(syntax/loc stx | |
(define name | |
(let ([cache (make-hash)]) | |
(lambda (args ...) | |
(define arglist (list args ...)) | |
(cond | |
[(hash-has-key? cache arglist) | |
(hash-ref cache arglist)] | |
[else | |
(define result (let () body ...)) | |
(hash-set! cache arglist result) | |
result])))))])) | |
;; Pascal's triangle | |
(define/memo (t m n) | |
(cond | |
[(or (< m 0) (>= m n)) | |
0] | |
[(= m 0) | |
1] | |
[(= m (sub1 n)) | |
1] | |
[else | |
(+ (t (sub1 m) (sub1 n)) | |
(t m (sub1 n)))])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
.rkt
, then GitHub knows to syntax-highlight it as Racket.hash-ref!
function is very useful for writing this program, I think your wholelambda
body could be just(hash-ref! cache (list args ...) (lambda () body ...))
.