Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom concat (++) operator in haskell

Is it possible to define my own ++ operator for a custom data type in Haskell?

I have:

data MyType = MyType [String]

and I would like to define my own concatenation operator as:

instance ? MyType where
    (MyType x) ++ (MyType y) = MyType (x ++ y)

I can't seem to find the name of the instance class anywhere.

like image 648
Wesley Tansey Avatar asked Nov 27 '12 23:11

Wesley Tansey


1 Answers

If you don't insist on calling the operator (++),

import Data.Monoid

instance Monoid MyType where
    (MyType x) `mappend` (MyType y) = MyType (x ++ y)
    mempty = MyType []

Then you can use

(<>) :: Monoid m => m -> m -> m

which is an alias for mappend (I thought it was already a type class member, but it isn't :/). Lists hava a Monoid instance where mappend is (++), so that would do what you desire. The Monoid instance also gives you

mconcat :: Monoid m => [m] -> m

which you can use to concatenate a list of MyTypes.

like image 86
Daniel Fischer Avatar answered Oct 02 '22 07:10

Daniel Fischer