[英]Custom concat (++) operator in haskell
Is it possible to define my own ++
operator for a custom data type in Haskell? 是否可以在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 :/). 这是mappend
的别名(我认为它已经是类型类成员,但它不是:/)。 Lists hava a Monoid
instance where mappend
is (++)
, so that would do what you desire. 列出了一个Monoid
实例,其中mappend
是(++)
,因此可以做你想要的。 The Monoid
instance also gives you Monoid
实例也为您提供
mconcat :: Monoid m => [m] -> m
which you can use to concatenate a list of MyType
s. 您可以使用它来连接MyType
列表。
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. 所以,它只是GHC.Base
模块中定义的简单函数。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.