[Haskell-beginners] Question regarding to type classes
Johannes Engels
johannes.engels at hft-stuttgart.de
Sat Sep 24 19:21:17 CEST 2011
Dear list members,
as an exercise, I tried to define a type class for structures with
ordered key values. The key values could be numbers, but also strings.
For instance, I intend to define an address list containing records with
names as key values. So far, my type class definition contains a
function "key", which should extract the key values from the structures,
and a function which compares the key values. So I tried:
class StructsWithOrderedKeys a where
-- no default definition for key
key :: (Ord b) => a -> b
(<?) :: a -> a -> Bool
x <? y = (key x) < (key y)
Here I get the following error message from GHCI:
"Ambiguous type variable 'b' in the constraint:
'Ord b' arising from a use of 'key' ...
Probable fix: add a type signature that fixes these type variable(s)"
Could anybody explain what ambiguity arises here? As the arguments of
(<?) are of the same type, I expected also the results (key x) and (key
y) to be of the same type, which should be by the type constraint for
"key" an instance of Ord. Why I am not allowed to use "key" in the
definition of (<?) ?
I would be grateful for any hint!
Johannes
More information about the Beginners
mailing list