Haskell caches results of pure function calls, one of the many reasons for the separation between pure and impure behavior. Yet this function, which should run in O(n) where n is 50
below, runs really slowly:
lucas 1 = 1
lucas 2 = 3
lucas n = lucas (n-1) + lucas (n-2)
map (lucas) [1..50]
The first thirty terms or so together compute in under a second, then 31 takes half a second or so, 32 takes a full second, 33 takes a few seconds, 34 takes 6 seconds, 35 takes 11 seconds, 36 takes 17 seconds...
Why is this function so slow? If the GHC interactive runtime is caching results, then each call to lucas
should only involve summing of the two previous cached terms. One addition operation to find term 3, one additional addition to find term 4, one additional addition to find term 5, so term 50 is reached with only 48 additions total considering caching. The function shouldn't take anywhere near a second to find at least the first few thousand terms, why is the performance so terrible?
I've been waiting for more than half an hour now for lucas 500
to compute.