Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Racket doesn't have a built-in memorization, but you can define a "define/mem" macro to handle the memorization details and you can reuse it later. This way, the example of the article runs in O(n) time without other changes:

  #lang racket
  
  (define-syntax-rule (define/mem (name arg) body ...)
    (begin
      (define cache (make-hash))
      (define (name arg)
        (hash-ref! cache arg (lambda () body ...)))))
  
  (define/mem (fib n)
    (cond
      [(= n 0) 0]
      [(= n 1) 1]
      [else (+ (fib (- n 1)) (fib (- n 2)))]))
  
  (fib 100)
But be careful, because this is O(n) in memory because the calculated values are never collected.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: