Can you overload + in haskell?

后端 未结 5 1326
深忆病人
深忆病人 2020-11-30 03:09

While I\'ve seen all kinds of weird things in Haskell sample code - I\'ve never seen an operator plus being overloaded. Is there something special about it?

Let\'s

5条回答
  •  情话喂你
    2020-11-30 03:24

    If you only want (+) operator rather than all the Num operators, probably you have a Monoid instance, for example Monoid instance of pair is like this:

    class (Monoid a, Monoid b) => Monoid (a, b) where
        mempty = (mempty, mempty)
        (a1, b1) `mappend` (a2, b2) = (a1 `mappend` a2, b1 `mappend` b2)
    

    You can make (++) a alias of mappend, then you can write code like this:

    (1,2) ++ (3,4) == (4,6)
    ("hel", "wor") ++ ("lo", "ld") == ("hello", "world")
    

提交回复
热议问题