[Haskell-cafe] Re: Numeric type classes

Lennart Augustsson lennart at augustsson.net
Wed Sep 13 08:36:15 EDT 2006


The sum function really only needs the argument list to be a monoid.
And the same is true for the product function, but with 1 and * as  
the monoid operators.  Sum and product are really the same function. :)

I don't think Haskell really has the mechanisms for setting up an  
algebraic class hierarchy the right way.  Consider some classes we  
might want to build:
SemiGroup
Monoid
AbelianMonoid
Group
AbelianGroup
SemiRing
Ring
...

The problem is that going from, say, AbelianMonoid to SemiRing you  
want to add a new Monoid (the multiplicative) to the class.  So  
SemiRing is a subclass of Monoid in two different way, both for + and  
for *.
I don't know of any nice way to express this is Haskell.

	-- Lennart

On Sep 13, 2006, at 03:26 , ajb at spamcop.net wrote:

> G'day all.
>
> Quoting Jason Dagit <dagit at eecs.oregonstate.edu>:
>
>> I was making an embedded domain specific language for excel
>> spreadsheet formulas recently and found that making my formula
>> datatype an instance of Num had huge pay offs.
>
> Just so you know, what we're talking about here is a way to make that
> even _more_ useful by dicing up Num.
>
>> I can even use things like Prelude.sum to
>> add up cells.
>
> Ah, but the sum function only needs 0 and (+), so it doesn't need
> the full power of Num.  It'd be even _more_ useful if it worked on
> all data types which supported 0 and (+), but not necessarily (*):
>
>     sum :: (AdditiveAbelianMonoid a) => [a] -> a
>
>     product :: (MultiplicativeAbelianMonoid a) => [a] -> a
>
> Those are bad typeclass names, but you get the idea.
>
> Right now, to reuse sum, people have to come up with fake
> implementations for Num operations that simply don't make sense on
> their data type, like signum on Complex numbers.
>
>>  All I really needed was to define Show and Num
>> correctly,  neither of which took much mental effort or coding  
>> tricks.
>
> You also needed to derive Eq, which gives you, in your case,  
> structural
> equality rather than semantic equality (which is probably  
> undecidable for
> your DSL).
>
> Cheers,
> Andrew Bromage
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list