Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Memoizing Fibonacci Sequence Generator (See related posts)

Generates a list containting the fibonacci-sequence out to n. It is also a memoizing function so a second call to the same n will be greatly faster.

   1  
   2  
   3  (let ((cache (make-hash-table :test #'equal)))
   4  	     (defun fibonacci-sequence (n)
   5  	       "Calculates the a Fibonacci Sequence of n integers."
   6  	       (declare (optimize speed))
   7  	       (declare (type number n))
   8  	       (labels ((get-fib (x seq)
   9  			  (if (= x n)
  10  			      (setf (gethash n cache) (nreverse seq))
  11  			      (if (cdr seq)
  12  				  (get-fib (+ x 1) (push (+ (first seq)
  13  							    (second seq))
  14  							 seq))
  15  				  (get-fib (+ x 1) (push 1 seq))))))
  16  		 (or (gethash n cache)
  17  		     (get-fib 0 nil))))
  18  	     (defun fib-hash (n)
  19  	       (gethash n cache))
  20  	     (defun fib-clear ()
  21  	       (setf cache (make-hash-table :test #'equal))))
  22  

You need to create an account or log in to post comments to this site.


Click here to browse all 5556 code snippets

Related Posts