1

I am working through the book https://www.packtpub.com/application-development/haskell-high-performance-programming and at moment, I am trying to understand the memoization.

It shows the following memoization function:

fib_mem :: Int -> Integer
fib_mem = (map fib [0..] !!)
where fib 0 = 1
      fib 1 = 1
      fib n = fib_mem (n-2) + fib_mem (n-1)  

In the book, it says:

So if fib_mem is defined at the top level, the results will persist in memory over the lifetime of the programm itself!

What does it mean, define at the top level?

softshipper
  • 32,463
  • 51
  • 192
  • 400

1 Answers1

4

"Top-level" is a synonym for "REPL", or if you use a source code file, it's its most outer scope -- it's global scope.

Traditionally, in Lisp, loading source code file was as if you executed its top level statements by typing them at the REPL one by one.

see also: How is this fibonacci-function memoized?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • 1
    FWIW I believe that for `fib_mem` to be memoized, it must be a CAF in addition to being a top-level declaration. So the book was not as precise as perhaps it could have been. https://wiki.haskell.org/Memoization#Memoising_CAFS – Rein Henrichs Feb 14 '19 at 02:54
  • @ReinHenrichs you are absolutely right. with these kinds of what looks like almost self-published books, it's always a gamble. --- It must also have a monomorhic type, I believe, as is discussed on the entry I linked IIRC. – Will Ness Feb 14 '19 at 06:43
  • Packt is basically a book mill. – Rein Henrichs Feb 14 '19 at 07:19