Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared value gets (unnecessarily) evaluated multiple times in Haskell

Tags:

haskell

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.

like image 655
Vlad the Impala Avatar asked Jan 24 '26 21:01

Vlad the Impala


1 Answers

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).

like image 155
ehird Avatar answered Jan 26 '26 15:01

ehird