Reputation: 284
I know there is no "cast" in Haskell but I have this expression:
o = sum . takeWhile (< 10000) . filter odd . map (^2) $ [1..]
I would like to have the result as a Double. I tried:
g :: (Integral c, Double b) => [c] -> b
g =sum . takeWhile (< 10000) . filter odd . map (^2)
and other things like that... I always get an error. How can I do?
Upvotes: 1
Views: 3946
Reputation: 1495
How about
g :: [Integer] -> Double
g = fromInteger . sum . takeWhile (< 10000) . filter odd . map (^2)
Or, you could convert the list to [Double] before the sum by
g = sum . map fromInteger . takeWhile (< 10000) . filter odd . map (^2)
There is no generic cast in Haskell, but there are functions (like fromInteger and fromRational) which can convert from a particular type to a desired type. The type of fromIntegral is
fromIntegral :: (Num b, Integral a) => a -> b
It will convert an Integral value to any kind of Num value.
Upvotes: 4