[Haskell-beginners] Question regarding to type classes
Antoine Latter
aslatter at gmail.com
Sat Sep 24 19:42:33 CEST 2011
On Sat, Sep 24, 2011 at 12:21 PM, Johannes Engels
<johannes.engels at hft-stuttgart.de> wrote:
> 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 (<?)
> ?
>
If a function has type:
> key :: (Ord b) => a -> b
You have declared that the type 'b' can be whatever the caller wants
(given the Ord constraint).
So in the computations:
> (key x) > (key y)
You haven't told it *which* 'b' you want to pick. And because the
return value is consumed by a polymorphic function, the type inference
engine doesn't have anything to go on.
Does that make sense?
Antoine
More information about the Beginners
mailing list