[Haskell-cafe] Type inference problem

Joel Björnson joel.bjornson at gmail.com
Sun Aug 6 17:20:19 EDT 2006


Hi.
I have a type inference related problem which causes me some confusion. The
following is a simplified example capturing the key aspects.
First of all, consider a data type (here called) Elem and a type class
IsElem.

data Elem = E

class IsElem a where
  toElem :: a -> Elem


instance IsElem Elem where
  toElem = id

instance Show a => IsElem a where
  toElem _ = E

Values of type Elem along with all instances of Show,  instansitates the
IsElem class.
What I want to achieve is the enabling of definitions of classes/member
functions corresponding to the following.

class SetId t v r | t -> r where
  setId :: t -> v -> r

And to instantiate the class, allowing 'setId' to produce values of type
Elem as in

instance SetId Elem String Elem where
  setId x _ = x

Note that the fundep (t -> r) enables the type checker to uniquely determine
the return type of setId, depending on it's first argument.
It is now possible to write function definitions according to

myElem = E `setId` "id"

Checking the type of 'myElem' using ghci confirms that it has type 'Elem'.
(Because of the E and the fundep)
So far, so good... However, problems arises trying to define the function :

test = toElem myElem

Yielding the error message : 'No instance for (Show Elem) arising use of
`toElem` at ...'

For some reason it seems like the type checker picks the *wrong* 'toElem',
and that the type of 'myElem' can't be properly determined (without adding
explicit type signatures). It seems strange though the the type of myElem
really can be determined and that the instance (IsElem Elem) is more
specific then the instance for Show types.

Anyway, I just realised that turning off the 'monomorphism-restriction'
solves the problem. (Don't know why though).
Is this *the* recommended solution here and is there any general policy
regarding the flag ?

Help/explanations are appreciated!

Thanks a lot
/Joel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org//pipermail/haskell-cafe/attachments/20060806/94cd45f6/attachment.htm


More information about the Haskell-Cafe mailing list