[Haskell-beginners] Types and the difference between GHCi interactive and a file

Russ Abbott russ.abbott at gmail.com
Sun Sep 26 16:46:35 EDT 2010


The following runs without a problem.

Prelude> let null' xs = xs == []
null' :: (Eq a) => [a] -> Bool

Prelude> let main' = do print (null' [])
main' :: IO ()

Prelude> main'
True
it :: ()

But if I put essentially the same code in a file and try to load the file I
get an error.

File: Null

null' xs = xs == []

main = do print (null' [])


Prelude> :load "Null.hs"
[1 of 1] Compiling Main             ( Null.hs, interpreted )

Null.hs:3:17:
    Ambiguous type variable `a' in the constraint:
      `Eq a' arising from a use of `null'' at Null.hs:3:17-24
    Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.

Why is that?


I had thought that the ambiguity was referring to the type of [] in the
print statement, i.e., that GHC can't figure out the type of [].  If I
modify the print statement to be   print ( null' ([] :: [Int]) )  everything
is ok.

But if that's the case, why is this not a problem at the interactive level?

Here is a related question.  In the following what does it mean to say that
x is of type [a] where "a" is a type variable?

Prelude> let x = []
x :: [a]

For example,

Prelude> x == (tail [1 :: Int])
True
it :: Bool

Prelude> x == (tail [1 :: Float])
True
it :: Bool

Prelude> (tail [1 :: Int]) == (tail [1 :: Float])

<interactive>:1:28:
    Couldn't match expected type `Int' against inferred type `Float'
    In the expression: 1 :: Float
    In the first argument of `tail', namely `[1 :: Float]'
    In the second argument of `(==)', namely `(tail [1 :: Float])'

Can a value like the value of x really be of an incompletely specified type?

I couldn't do that in the file.

When I tried the following in the file,

print (null' ([] :: (Eq a) => a))

I got this error message on loading the file.

Null.hs:3:24:
    Couldn't match expected type `a1' against inferred type `[a]'
      `a1' is a rigid type variable bound by
           an expression type signature at Null.hs:3:34
    In the first argument of `null'', namely `([] :: (Eq a) => a)'
    In the first argument of `print', namely
        `(null' ([] :: (Eq a) => a))'
    In the expression: print (null' ([] :: (Eq a) => a))


Thanks.

-- Russ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100926/b6b8e7a3/attachment.html


More information about the Beginners mailing list