[Haskell-cafe] Odd behavior with Num instance for lists (was: f^n for functional iteration)
Mark Fredrickson
mark.m.fredrickson at gmail.com
Fri Dec 13 16:57:44 UTC 2013
On Fri, Dec 13, 2013 at 8:59 AM, Antonio Nikishaev <me at lelf.lu> wrote:
>
> http://hackage.haskell.org/package/NumInstances
>
The previous exchange prompted me to whip up a Num instance for lists:
instance Num a => Num [a] where
negate = fmap negate
(+) = zipWith (+)
(*) = zipWith (+)
fromInteger x = [fromInteger x]
abs = fmap abs
signum = fmap signum
It mostly behaves how one would expect:
let a = [1,2,3]
ghci> let b = [4,5,6,7]
ghci> a + b
[5,7,9]
ghci> 1 + a
[2]
I was wondering whey `1 + a` succeeds. At first I thought it could be the
`fromInteger` definition, but this explanation were true, I should be able
to add integers and doubles freely, which I can't:
ghci> fromInteger (1::Integer) + (1.0::Double)
2.0
ghci> (1::Integer) + (1.0::Double)
<interactive>:30:17:
Couldn't match expected type `Integer' with actual type `Double'
In the second argument of `(+)', namely `(1.0 :: Double)'
...
Thanks for enlightening me.
-M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20131213/9e17337f/attachment.html>
More information about the Haskell-Cafe
mailing list