[Haskell-cafe] Num instances for 2-dimensional types
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?
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
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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe