++
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
(すでに型クラスのメンバーだと思っていましたが、そうではありません:/)。リストには is の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
(++)
operator はどの型クラスにも属していません。これは簡単に確認できます:
$ 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)