O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How it works...

We have revisited fibonacci numbers in this recipe. Here, we used the State Monad to store the intermediate results while calculating the fibonacci number. We defined a map between the fibonacci index and its number as a state. Two functions getFib and putFib are defined. The getFib function uses State Monad function GET to get the map and checks if the result was previously cached. If the result was not cached before, then it proceeds by calculating the n-1th and n-2th fibonacci numbers and caching all intermediate results. In fact, since the n-1th number calculation will involve the n-2th number as well, the calculation will be quickly done (O(n) complexity)

We used the function execState to run our fibonacci number calculation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required