3
\$\begingroup\$

Here's my type:

data Tree a = Empty | Node a (Tree a) (Tree a)

Here's the instance declaration for Monoid:

instance (Monoid a) => Monoid (Tree a) where
    mempty = Empty
    mappend Empty Empty = Empty
    mappend Empty t = t
    mappend t Empty = t
    mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend val val') (mappend ta ta') (mappend tb tb'))

This compiles, but it was tedious to write and very repetitive. Is there a better way of doing this?

\$\endgroup\$
1
  • \$\begingroup\$ In addition to @Garrison's answer it might be nicer to use the infix <> operator in the last line in the place of mappend. \$\endgroup\$
    – Redu
    Commented Oct 30, 2019 at 19:30

1 Answer 1

2
\$\begingroup\$

You can remove mappend Empty Empty = Empty because that case will be caught by mappend Empty t = t.

instance (Monoid a) => Monoid (Tree a) where
    mempty = Empty
    mappend Empty t = t
    mappend t Empty = t
    mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend val val') (mappend ta ta') (mappend tb tb'))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.