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.
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 MyType
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With