Added memoization.  Not purely functional but referentially transparent.