Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created September 29, 2012 22:59
Show Gist options
  • Save dyoo/3805375 to your computer and use it in GitHub Desktop.
Save dyoo/3805375 to your computer and use it in GitHub Desktop.
Pascal's triangle memoized
#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)))]))
@samth
Copy link

samth commented Sep 30, 2012

  • If you give the gist a filename ending in .rkt, then GitHub knows to syntax-highlight it as Racket.
  • You might want to look at Dave Herman's memoize.plt Planet package, which does something similar.
  • The hash-ref! function is very useful for writing this program, I think your whole lambda body could be just (hash-ref! cache (list args ...) (lambda () body ...)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment