Break `abs` into two aspects

Mario Blažević mblazevic at stilo.com
Wed Feb 5 20:18:52 UTC 2020


On 2020-02-04 11:32 a.m., Zemyla wrote:
> It really doesn't matter if it's not "interesting" or not surjective for 
> some Semirings. It should be included, because:

	I fully agree, and I'll add another reason you left out. The presence 
of fromNatural would allow defaulting of Num's fromInteger as

 > fromInteger i
 >     | i >= 0 = fromNatural (fromInteger i)
 >     | otherwise = negate . fromInteger . negate $ i


> (a) Even for semirings where it is "interesting", it's not surjective 
> (for instance, Rational or Double)
> (b) It's a method with a default definition, so you don't have to expend 
> any mental effort on it
> (c) A lot of instances have uninteresting methods: for instance, (*>) 
> and (<*) for Applicative ((->) e) are const id and const respectively. 
> Haskell adds methods to classes when they're always possible and 
> sometimes useful/interesting/faster, rather than when they're always 
> interesting.
> (d) It's useful for Semiring-generic methods and instances.
> (e) It can achieve an asymptotic speedup on some instances. Like, if you 
> have Semiring a => Semiring (f a) for some type f, then you can have 
> fromNatural n = pure (fromNatural n) instead of doing the whole O(log n) 
> song and dance with the default definition. Also, your example admits a 
> simple definition:
>    fromNatural n = if n == 0 then S.empty else S.singleton True
> (f) "zero" and "one" can be defined in terms of fromNatural, for 
> programmers who only need to define that:
>    zero = fromNatural 0
>    one = fromNatural 1
> This leads to the MINIMAL pragma on Semiring being {-# MINIMAL plus, 
> times, (zero, one | fromNatural) #-}
> (g) If it's not included in the class, but in some subclass 
> (NaturalSemiring, you proposed), but it's possible from the class, then 
> people will just define and use the O(log n) version instead of 
> requiring the subclass, leading to wasted effort and duplicated code.



More information about the Libraries mailing list