Can you overload + in haskell?

后端 未结 5 1327
深忆病人
深忆病人 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:37

    Overloading in Haskell is only available using type classes. In this case, (+) belongs to the Num type class, so you would have to provide a Num instance for your type.

    However, Num also contains other functions, and a well-behaved instance should implement all of them in a consistent way, which in general will not make sense unless your type represents some kind of number.

    So unless that is the case, I would recommend defining a new operator instead. For example,

    data Pair a b = Pair a b
        deriving Show
    
    infixl 6 |+| -- optional; set same precedence and associativity as +
    Pair a b |+| Pair c d = Pair (a+c) (b+d)
    

    You can then use it like any other operator:

    > Pair 2 4 |+| Pair 1 2
    Pair 3 6
    

提交回复
热议问题