fork download
  1. (defun memoize (fn)
  2. (let ((table (make-hash-table)))
  3. (lambda (x)
  4. (or (gethash x table)
  5. (setf (gethash x table) (funcall fn x))))))
  6.  
  7. ;; Используется так:
  8. (time
  9. (let ((fn (memoize (lambda (x) (sleep x) x))))
  10. (print (funcall fn 3))
  11. (print (funcall fn 3))))
  12.  
  13. ;; Или так:
  14. (defun yoba (x) (sleep x) x)
  15. (setf (fdefinition 'yoba) (memoize #'yoba))
  16.  
  17. (time (progn (print (yoba 1))
  18. (print (yoba 1))))
Success #stdin #stdout 0s 10520KB
stdin
Standard input is empty
stdout
3 
3 
Real time: 3.014789 sec.
Run time: 0.001 sec.
Space: 1464 Bytes
1 
1 
Real time: 1.004886 sec.
Run time: 0.0 sec.
Space: 656 Bytes