[Haskell-cafe] Odd behavior with Num instance for lists (was: f^n for functional iteration)
bob at redivi.com
Fri Dec 13 17:24:56 UTC 2013
On Fri, Dec 13, 2013 at 8:57 AM, Mark Fredrickson <
mark.m.fredrickson at gmail.com> wrote:
> On Fri, Dec 13, 2013 at 8:59 AM, Antonio Nikishaev <me at lelf.lu> wrote:
> 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
> ghci> 1 + a
> 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)
> ghci> (1::Integer) + (1.0::Double)
> Couldn't match expected type `Integer' with actual type `Double'
> In the second argument of `(+)', namely `(1.0 :: Double)'
> Thanks for enlightening me.
`1 + a` works for the same reason `1 + (1.0::Double)` works: type
inference. `1 + a` in this instance is equivalent to `(1 :: Num [Integer])
+ a` which should compile down to something equivalent to `fromInteger 1 +
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe