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

时间:2012-11-27 23:20:37

标签: haskell operators

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

我有:

data MyType = MyType [String]

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

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

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

3 个答案:

答案 0 :(得分:13)

如果您不坚持致电运营商(++)

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,以便按您的意愿行事。 {{1}}实例也为您提供了

{{1}}

可用于连接{{1}} s。

的列表

答案 1 :(得分:4)

最容易做到

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

答案 2 :(得分:3)

(++)运算符不属于任何类型类。您可以轻松查看:

$ 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)
相关问题