[Haskell-cafe] Odd behavior with Num instance for lists (was: f^n for functional iteration)

Erik Hesselink hesselink at gmail.com
Fri Dec 13 19:04:40 UTC 2013


On Fri, Dec 13, 2013 at 5:57 PM, 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

Wouldn't it make more sense to have fromInteger be `repeat .
fromInteger`? This would make it an instance for ZipList, not list.
You could even give a general instance for applicatives:

instance (Num a, Applicative f) => Num (f a) where
  negate = fmap negate
  (+) = liftA2 (+)
  (*) = liftA2 (*)
  fromInteger = pure . fromInteger
  abs = fmap abs
  signum = fmap signum

For ZipList this behaves like your instance, except fromInteger
produces an infinite list like 'repeat . fromInteger'. The list
instance instead computes all possiblities:

ghci> [1,2,3] + [4,5,6,7]
[5,6,7,8,6,7,8,9,7,8,9,10]

Erik


More information about the Haskell-Cafe mailing list