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.
easiest it would be to do
import Prelude hiding ((++))
import qualified Prelude as P
data MyType = MyType [String]
class PlusAble a where
infixr 5 ++
(++) :: a -> a -> a
instance PlusAble MyType where
(MyType x) ++ (MyType y) = MyType (x P.++ y)
-- EDIT:
instance PlusAble [a] where
x ++ y = x P.++ y
(++)
operator does not belong to any type class. You can easily check this:
$ ghci
Prelude> :info (++)
(++) :: [a] -> [a] -> [a] -- Defined in `GHC.Base'
infixr 5 ++
So, it's just simple function defined in GHC.Base
module. You can hide it and define your own one:
import Prelude hiding ((++))
import qualified Prelude -- to get hidden (++) as Prelude.(++)
-- your brand new (++)
infixr 5 ++
(MyType x) ++ (MyType y) = MyType (x Prelude.++ y)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.