I read this answer which made it sound like when a shared value is evaluated, it is only evaluated once and then the result is stored. For example:
x = 2 + 2
y = 2 + x
z = 3 + x
Here, x is evaluated once and then stored as 4, and it is never evaluated again? At least that was my assumption. My code has a value that gets re-calculated every time it is referenced. It is a pure value. When would this happen, and how can I force Haskell to remember the value once it is calculated?
Example:
x = [1, 1, 2]
count = fst $ getCounts x
Here, count gets evaluated every time it is referenced.
As Daniel Wagner points out, the most likely scenario here is that count is not given an explicit type signature, but you've turned the monomorphism restriction off (e.g. with the NoMonomorphismRestriction language extension). This means that count has a type like
count :: (Num a) => a
This means that GHC treats count like a function (specifically, from the Num typeclass dictionary for any type a, to an a), and so the results are not shared, meaning its value is recomputed on every use.
The best solution is to give count an explicit type signature, e.g.
count :: Int
You should probably do the same for x, too (and, for that matter, all the other top-level definitions in your program).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With