Automatic propagation of monoidal mappend

Viewed 92

Let's say I have a monoid defined as this:

data TotalLine = TotalLine { totalQuantity :: Int, orderTotal :: Float }

instance Monoid TotalLine where
  mempty = zero
  mappend = add

As totalQuantity and orderTotal are both numbers they also form a monoid under (+) Is there any way to define

add :: TotalLine -> TotalLine -> TotalLine

so, Can I just propagate the mappend call on each field instead of having to manually define something like

add line1 line2 =
  TotalLine {
    totalQuantity = totalQuantity line1 + totalQuantity line2,
    orderTotal = orderTotal line1 + orderTotal line2
   }
3 Answers
Related