Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make a new data type Hashable

Tags:

haskell

Attempt to compile the following with ghc 7.8.2 on OS X 10.9.3

import Data.Hashable (Hashable, hash)

data Edge v = Edge v v deriving (Show)

instance (Eq v) => Eq (Edge v) where
  Edge x1 x2 == Edge y1 y2 =
    x1 == y1 && x2 == y2 || x1 == y2 && x2 == y1

instance (Hashable v) => Hashable (Edge v) where
  hash (Edge x1 x2) = (hash x1) + (hash x2)

fails with

Could not deduce (hashable-1.2.1.0:Data.Hashable.Class.GHashable
                    (GHC.Generics.Rep (Edge v)))
  arising from a use of ‘hashable-1.2.1.0:Data.Hashable.Class.$gdmhashWithSalt’
from the context (Hashable v)
  bound by the instance declaration at src/MinCut.hs:12:10-42
In the expression:
  hashable-1.2.1.0:Data.Hashable.Class.$gdmhashWithSalt
In an equation for ‘hashWithSalt’:
    hashWithSalt
      = hashable-1.2.1.0:Data.Hashable.Class.$gdmhashWithSalt
In the instance declaration for ‘Hashable (Edge v)’

What is wrong?

like image 244
Eldar Avatar asked May 28 '14 12:05

Eldar


1 Answers

The hackage docs for Data.Hashable states that the minimal implementation of Hashable is the function hashWithSalt — check out the documentation under the typeclass declaration (class Hashable a where).

So if you change your function to hashWithSalt, everything should work:

instance (Hashable v) => Hashable (Edge v) where
  hashWithSalt s (Edge x1 x2) = s + (hash x1) + (hash x2)
like image 165
Jakob Runge Avatar answered Oct 22 '22 09:10

Jakob Runge