memoize

memoize f -- produces, from a function f, a new function which behaves the same as f, but remembers previous answers to be provided the next time the same arguments are presented.

     i1 = fib = n -> if n <= 1 then 1 else fib(n-1) + fib(n-2)
     
     o1 = fib
     
     o1 : Function
     
     i2 = time fib 16
     
          -- used 0.37 seconds
     o2 = 1597
     
     i3 = fib = memoize fib
     
     o3 = fib
     
     o3 : Function
     
     i4 = time fib 16
     
          -- used 0.01 seconds
     o4 = 1597
     
     i5 = time fib 16
     
          -- used 0. seconds
     o5 = 1597
     

The function memoize operates by constructing a MutableHashTable in which the argument sequences are used as keys for accessing the return value of the function.

Warning: when the value returned by f is null, it will always be recomputed, even if the same arguments are presented.

See also original.

Go to main index.

Go to concepts index.