haskell中的自定义concat(++)运算符 [英] Custom concat (++) operator in haskell
问题描述
是否可以在Haskell中为自定义数据类型定义自己的 ++
运算符?
Is it possible to define my own ++
operator for a custom data type in Haskell?
I有:
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
这是 mappend
的别名(我认为它已经是一个类型成员,但它不是:/)。列出了一个 Monoid
实例,其中 mappend
是(++)
,这样会做你想做的事。 Monoid
实例也为您提供
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
您可以使用它连接 MyType
s。
which you can use to concatenate a list of MyType
s.
这篇关于haskell中的自定义concat(++)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!