[Haskell-cafe] Num instances for 2-dimensional types

Job Vranish jvranish at gmail.com
Mon Oct 5 10:29:02 EDT 2009


In what way is it not a number?

data MyNumber a = MyNum a a
   deriving (Show, Eq)

instance Functor MyNum where
  fmap f (MyNum a b) = MyNum (f a) (f b)

instance Applicative MyNum where
  pure a = MyNum a a
  MyNum f g <*> MyNum a b = MyNum (f a) (g b)

instance (Num a) => Num (MyNum a) where
  a + b = pure (+) <*> a <*> b
  a - b = pure (-) <*> a <*> b
  a * b = pure (*) <*> a <*> b
  negate a = pure negate <*> a
  abs a = pure abs <*> a
  signum = fmap signum
  fromInteger = pure . fromInteger

This instance obeys the commutative, distributive, and associative laws,
and the multiplicative, and additive identities. (at least, if the numbers
it contains satisfy those laws)
How is MyNum not a number?


Sönke Hahn:
  btw, I forgot to mention in my first email, but
      fromInteger n = (r, r) where r = fromInteger n
  is better than:
      fromInteger n = (fromInteger n, 0)
 as you get a lot of corner cases otherwise.

 I use fromInteger = pure . fromInteger, which when combined with my
Applicative instance, is effectively the same as your:  fromInteger n = (r,
r) where r = fromInteger n


- Job

On Mon, Oct 5, 2009 at 9:12 AM, Miguel Mitrofanov <miguelimo38 at yandex.ru>wrote:

>
>
> Sönke Hahn wrote:
>
>  I used to implement
>>
>>    fromInteger n = (r, r) where r = fromInteger n
>>
>> , but thinking about it,
>>    fromInteger n = (fromInteger n, 0)
>>
>> seems very reasonable, too.
>>
>
> Stop pretending something is a number when it's not.
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091005/4aaff28b/attachment-0001.html


More information about the Haskell-Cafe mailing list