Eq类型的纯脚本编写实现class

purescript writing implementation for Eq type class

我用纯脚本写了这段代码

module TypeClasses where
  import Prelude
  import Data.Array
  import Data.Number.Format(toString) 

  data Point = Point{x:: Number, y:: Number}
  instance showPoint :: Show Point where 
    show (Point {x, y}) = (toString x) <> ", " <> (toString y)    
  instance eqPoint :: Eq Point where
    eq p1 p2 = if (p1.x == p2.x && p1.y1 == p2.y2) then true else false

但我收到错误

Compiling TypeClasses
Error found:
in module TypeClasses
at src/TypeClasses.purs line 17, column 20 - line 17, column 22

  Could not match type

    { x :: t0
    | t1
    }

  with type

    Point


while checking that type Point
  is at least as general as type { x :: t0
                                 | t1
                                 }
while checking that expression p1
  has type { x :: t0
           | t1
           }
while checking type of property accessor p1.x
in value declaration eqPoint

where t0 is an unknown type
      t1 is an unknown type

See https://github.com/purescript/documentation/blob/master/errors/TypesDoNotUnify.md for more information,
or to contribute content related to this error.

您的代码有几个问题:

  • 您必须 解构 Point 参数才能使用您的实际坐标访问 "wrapped" 记录,如下所示:eq (Point p1) (Point p2)(这将解决你的类型错误)
  • .y1.y2 不存在,我猜你的意思是 .y
  • 提示:if something then true else false 可以缩短为 something

所以你最终会得到 Eq for Point 的这个实现:

instance eqPoint :: Eq Point where
  eq (Point p1) (Point p2) = p1.x == p2.x && p1.y == p2.y