fibonacci - Calculating fib using List construction in Haskell - speed differences -


if we've defined following:

lazyfib x y = x:(lazyfib y (x + y)) fib = lazyfib 1 1 

(from 7 languages in 7 weeks book). why does

fibnth x = head (drop (x-1) fib) 

evaluate slower

fibnth2 x = head (drop (x-1) (take (x) fib) 

? second 1 terminates infinite list required - intuitively expected (head) call terminate evaluation moment 1 item comes through "drop", regardless of whether there take limit on fib? can explain?

(updated timings reference):

> :set +s > fibnth 100000 259740693472217241661550340212759154148804853865176... (1.16 secs, 458202824 bytes) > fibnth2 100000 259740693472217241661550340212759154148804853865176.... (0.09 secs, 12516292 bytes) 

if flip order of 2 functions in source file or interpreter, see second function lot faster.

the reason? fib top level value gets evaluated once. on first call evaluate far needed, on second call breeze through list.

you can @ this question notes on when such evaluation behaviour expected. in nutshell, values non-polymorphic types memoized, while polymorphic values , function applications not.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -