Search code examples
purescript

purescript writing implementation for Eq type class


I wrote this code in purescript

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

but I get error

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.

Solution

  • A couple of issues with your code:

    • You have to deconstruct the Point parameters to access the "wrapped" record with your actual coordinates like this: eq (Point p1) (Point p2) (this will solve your type error)
    • .y1 and .y2 do not exist, I guess you mean .y
    • And as a hint: if something then true else false can be shortened to just something

    So you will end up with this implementation of Eq for Point:

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