繁体   English   中英

haskell中的自定义concat(++)运算符

[英]Custom concat (++) operator in haskell

是否可以在Haskell中为自定义数据类型定义自己的++运算符?

我有:

data MyType = MyType [String]

我想将自己的连接运算符定义为:

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

我似乎无法在任何地方找到实例类的名称。

如果你不坚持调用运算符(++)

import Data.Monoid

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

然后你可以使用

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

这是mappend的别名(我认为它已经是类型类成员,但它不是:/)。 列出了一个Monoid实例,其中mappend(++) ,因此可以做你想要的。 Monoid实例也为您提供

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

您可以使用它来连接MyType列表。

最容易做到的

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

(++)运算符不属于任何类型类。 你可以轻松检查这个:

$ ghci
Prelude> :info (++)
(++) :: [a] -> [a] -> [a]   -- Defined in `GHC.Base'
infixr 5 ++

所以,它只是GHC.Base模块中定义的简单函数。 你可以隐藏它并定义你自己的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM