[Haskell-cafe] Odd behavior with Num instance for lists (was: f^n for functional iteration)
Bob Ippolito
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:
>
>>
>> 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.
>
`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 +
a`.
-bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20131213/01045a5d/attachment.html>
More information about the Haskell-Cafe
mailing list