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
countis not given an explicit type signature, but you’ve turned the monomorphism restriction off (e.g. with theNoMonomorphismRestrictionlanguage extension). This means thatcounthas a type likeThis means that GHC treats
countlike a function (specifically, from theNumtypeclass dictionary for any typea, to ana), 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.
You should probably do the same for
x, too (and, for that matter, all the other top-level definitions in your program).