Python的==,在Haskell的土地上

时间:2015-07-17 03:23:34

标签: haskell

示例代码,显示如何使用==运算符在Python中比较两个对象:

class Person:
  def __init__(name):
    this.name = name

  def __eq__(nextPerson):
    if this.name == nextPerson.name:
      return True
    return False

if __name__ == '__main__':
   personOne = Person("saran")
   personTwo = Person("madhavan")
   personThree = Person("saran")
   print personOne == personTwo
   print personOne == personThree

必须打印:

False
True

如何在Haskell中使用Eq类型类编写上述代码?

1 个答案:

答案 0 :(得分:4)

data Person = Person { name::String } deriving (Show)

instance Eq Person where
    x == y = (name x) == (name y)

main = do
    let personOne = Person { name="saran" }
    let personTwo = Person { name="madhavan" }
    let personThree = Person { name="saran" }
    print $ personOne == personTwo
    print $ personOne == personThree