Given the following:
debug = flip Debug.Trace.trace
foo = [1,2,3]
myRandom :: [a] -> IO Int
myRandom x =
let lx = Prelude.length x
in System.Random.randomRIO (0, lx) `debug` show lx
test = myRandom foo
multiple runs of test
will produce a random number every time, but only the first call will print the length of the function argument. I assume it's only calculated once. Does Haskell memoize every function by default (in this case length
)? How does this work in detail?
lx = length x
. – Willem Van Onsemtest
is not a function; it's anIO Int
value. You can execute that action multiple times, butmyRandom
(which callsdebug
) itself is only called once. – chepnertest
I can't see how Haskell does it? – Michiel Borkenttest
. Computing theIO Int
action itself produces thetrace
output. The action is only computed once (the first time it's used), then reused. – melpomene