bjornbm / dimensional-classic

Automatically exported from code.google.com/p/dimensional
BSD 3-Clause "New" or "Revised" License
3 stars 1 forks source link

Sum of Quantity should be a Monoid #42

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Quantity should provide a Monoid instance for Sum. Since FlexibleInstances is 
already used, it could be instance Monoid (Sum a) => Monoid (Sum (Quantity d 
a)) but Num a => Monoid (Sum (Quantity d a)) would suffice and would be more 
legible.

Original issue reported on code.google.com by tor...@gmail.com on 30 Aug 2014 at 6:33

GoogleCodeExporter commented 9 years ago

Original comment by bjorn.bu...@gmail.com on 2 Sep 2014 at 8:18

GoogleCodeExporter commented 9 years ago
This will overlap with the existing instance `Num a => Monoid (Sum a)`. Maybe 
by using overlapping instances the more specific instance can be picked. But I 
think it is better to define your own Sum wrapper if/when you need it:

> newtype Sum' a = Sum' { getSum' :: a } deriving (..)

> instance Num a => M.Monoid (Sum' (Quantity d a)) where
>   mempty = Sum' _0
>   Sum' x `mappend` Sum' y = Sum' (x + y)  -- (+) from dimensional.

Original comment by bjorn.bu...@gmail.com on 15 Sep 2014 at 1:50

GoogleCodeExporter commented 9 years ago
By the way, we are drafting a version of dimensional using DataKinds and Closed 
Type Families on Github, and there we have tentatively put in:

+{-
+Since quantities form a monoid under addition, but not under multiplication 
unless they are dimensionless,
+we will define a monoid instance that adds.
+-}
+instance (Num a) => Monoid (Quantity d a) where
+  mempty = _0
+  mappend = (+)

See 
https://github.com/bjornbm/dimensional-dk/commit/bd0e17ae462633f78a2d0803c33afa7
29d7eb748

Please comment if you this would meet your need, or if you think it is a 
misfeature!

Original comment by bjorn.bu...@gmail.com on 19 Sep 2014 at 8:31

GoogleCodeExporter commented 9 years ago
After filing this, I realized that the thing I was going to use it for was 
going to run into stability issues if it used naive summation, so I made a 
version that uses one of the more stable algorithms. I still think it's a good 
idea.

Original comment by tor...@gmail.com on 19 Sep 2014 at 8:35

GoogleCodeExporter commented 9 years ago
Ok, thanks for the comment. Anyway, you're welcome to follow the development at 
https://github.com/bjornbm/dimensional-dk if you want a glimpse of the future, 
and to influence it. The issues section should give a good idea of the design 
choices being contemplated.

Original comment by bjorn.bu...@gmail.com on 19 Sep 2014 at 8:49