I have function as below:
foo :: Int -> a -> [a]
foo n v = bar n
where
bar :: Int -> [a]
bar n = take n $ repeat v
using ghci report this error:
Couldn't match type `a' with `a1'
`a' is a rigid type variable bound by
the type signature for foo :: Int -> a -> [a] at hs99.hs:872:1
`a1' is a rigid type variable bound by
the type signature for bar :: Int -> [a1] at hs99.hs:875:9
Expected type: [a1]
Actual type: [a]
In the expression: take n $ repeat v
In an equation for `bar': bar n = take n $ repeat v
If removing the type declaration of bar, code can be compiled without error. So what’s the proper type declaration of bar here? And why error happens, because type declaration of bar is more generic than definition of bar (which is bound to some type in foo)?
Thanks for any help!
The
ainand the
ainare different type variables with the same name.
To get the behaviour you expect, turn on the ScopedTypeVariables extension (e.g. by inserting
{-# LANGUAGE ScopedTypeVariables #-}at the top of your source file), and change the type signature offootoWhen ScopedTypeVariables is not enabled, it is as if your original code was written like this:
It is not true to say that ghci implicitly uses ScopedTypeVariables if you leave out the type annotation for
bar.Instead, the type annotation you give for
barconflicts with the type ghci infers — you are assertingbarhas a type that ghci knows it can’t have.When you remove the type annotation, you remove the conflict.
ScopedTypeVariables changes the meaning of type annotations that you supply. It does not effect how ghc infers types.