function - How to tell whether Haskell will cache a result or recompute it? -
i noticed haskell pure functions somehow cached: if call function twice same parameters, second time result computed in no time.
- why happen? ghci feature or what?
- can rely on (ie: can deterministically know if function value cached)?
- can force or disable feature function calls?
as required comments, here example found on web:
isprime = isprimehelper primes isprimehelper (p:ps) | p*p > = true | `mod` p == 0 = false | otherwise = isprimehelper ps primes = 2 : filter isprime [3,5..]
i expecting, before running it, quite slow, since keeps accessing elements of primes
without explicitly caching them (thus, unless these values cached somewhere, need recomputed plenty times). wrong.
if set +s
in ghci (to print timing/memory stats after each evaluation) , evaluate expression primes!!10000
twice, get:
*main> :set +s *main> primes!!10000 104743 (2.10 secs, 169800904 bytes) *main> primes!!10000 104743 (0.00 secs, 0 bytes)
this means @ least primes !! 10000
(or better: whole primes
list, since primes!!9999
take no time) must cached.
primes
, in code, not function, constant, in haskellspeak known caf. if took parameter (say, ()
), 2 different versions of same list if calling twice, caf, exact same list both times;
as ghci top-level definition, primes
never becomes unreachable, head of list points (and tail/the rest of computation) never garbage collected. adding parameter prevents retaining reference, list garbage collected (!!)
iterates down find right element, , second call (!!)
force repetition of whole computation instead of traversing already-computed list.
note in compiled programs, there no top-level scope in ghci , things garbage collected when last reference them gone, quite before whole program exits, caf or not, meaning first call take long, second 1 not, , after that, "the future of program" not referencing caf anymore, memory caf takes recycled.
the primes package provides function takes argument (primarily, i'd claim) reason, carrying around half terabyte of prime numbers might not 1 wants do.
if want down bottom of this, recommend reading stg paper. doesn't include newer developments in ghc, great job of explaining how haskell maps onto assembly, , how thunks eaten strictness, in general.
Comments
Post a Comment