Issue with simple code from "Purescript by example"

Hello everybody,

I am starting to learn Purescript reading “Purescript by example” and following along trying the code listed there.

I have stumbled upon a problem (reading paragraph 6.12) and I am not able to understand how to fix.

I am using purescript 0.12.0, and the following snippet of code does not compile.
I compile the project using pac-package, and I am using the following version of package-set: source: https://github.com/clipperz/package-sets.git, set: psc-clipperz-0.0.1

module Main where

import Data.Eq (class Eq, eq)
import Data.EuclideanRing (mod)
import Data.Function (on)
import Data.Semiring ((+), (*))

newtype HashCode = HashCode Int

hashCode :: Int -> HashCode
hashCode h = HashCode (h `mod` 65535)

class Eq a <= Hashable a where
    hash :: a -> HashCode

combineHashes :: HashCode -> HashCode -> HashCode
combineHashes (HashCode h1) (HashCode h2) = hashCode (73 * h1 + 51 * h2)

hashEqual :: forall a. Hashable a => a -> a -> Boolean
hashEqual = eq `on` hash

The error reported is: No type class instance was found for Data.Eq.Eq HashCode.

As far as I can understand, it seems like the compiler is not able to infer which implementation of ‘eq’ should be used for the new type ‘HashCode’.
I would have expected that, being HashCode just a “renamed” Int, the compiler could have used the ‘eq’ implementation available for Int also for HashCode values.

What am I missing?

Thanks,

Giulio Cesare

You can do this be first deriving a Newtype instance and then telling the compiler to defer to instances of the underlying type using derive newtype instance.

In this case:

newtype HashCode = HashCode Int

derive instance newtypeHashCode :: Newtype HashCode _
derive newtype instance eqHashCode :: Eq HashCode

I’m not sure if this is missing from the book or there is some other issue affecting things here.

2 Likes

Thanks @paulyoung!

I need to study what the actual behaviour of the ‘derive’ clause is, but my code compiled and “worked” just adding the second line:
derive newtype instance eqHashCode :: Eq HashCode

I need to admit that the ‘derive’ instruction is included in the code for the book available for download; my fault for not looking into it before writing here, but as there was so little code involved I thought I was doing some stupid error there.

Anyway, thanks a million for the help.

Giulio Cesare

2 Likes