Reputation: 49095
Given this line of code (which I first saw in this answer):
pVal :: Num a => a
pVal = sum . map fromIntegral $ ([1..10000000] :: [Int])
If it's used as multiple types, is the expression completely reevaluated for each type? Is one result for each type kept around?
For example:
pInt :: Int
pInt = pVal
pDub :: Double
pDub = pVal
Upvotes: 3
Views: 101
Reputation: 139870
Technically, the Haskell standard doesn't specify. In practice, it's re-evaluated each time. You can verify this yourself using Debug.Trace
:
import Debug.Trace (trace)
pVal :: Num a => a
pVal = trace "evaluating..." $ sum . map fromIntegral $ ([1..10000] :: [Int])
Try it in GHCi:
> pVal :: Int
evaluating...
50005000
> pVal :: Int
evaluating...
50005000
However, binding this value to a concrete type will allow it to be re-used.
pInt :: Int
pInt = pVal
Notice there's no "evaluating..." the second time:
> pInt
evaluating...
50005000
> pInt
50005000
Upvotes: 12