
Am Donnerstag 13 August 2009 17:25:07 schrieb Robert Ziemba:
Can anyone help me understand the behavior of the following expressions in ghci? I was trying to construct a flipped function 'elem' that would accept a list of characters first but I ran into this problem with the type signature. Thank you.
Prelude Data.List Data.Char> :t elem elem :: (Eq a) => a -> [a] -> Bool -- OK Prelude Data.List Data.Char> :t (flip elem) (flip elem) :: (Eq a) => [a] -> a -> Bool -- OK this is what I want Prelude Data.List Data.Char> let fElem = (flip elem) Prelude Data.List Data.Char> :t fElem fElem :: [()] -> () -> Bool -- ?? Function will not accept a [Char]
It's the monomorphism restriction. If you bind a name by a simple pattern binding (like [let] fElem = flip elem) and don't give a type signature, it must have a monomorphic type and in ghci, that defaults to () for unconstrained type variables. Ways to fix the behaviour: 1. give an explicit type signature (good in code files anyway, but cumbersome at the ghci prompt) 2. make it a function binding: let fElem xs x = x `elem` xs let fElem xs = (`elem` xs) let fElem xs = flip elem xs 3. run ghci without the monomorphism restriction Prelude> :set -XNoMonomorphismRestriction Prelude> let fElem = flip elem Prelude> :t fElem fElem :: (Eq a) => [a] -> a -> Bool (that would be a good entry in your .ghci file anyway, you rarely want it unless you are a compiler writer)