Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function could not match type

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!

like image 856
Orup Avatar asked May 22 '12 20:05

Orup


2 Answers

The a in

foo :: Int -> a -> [a]

and the a in

    bar :: Int -> [a]

are 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 of foo to

foo :: forall a. Int -> a -> [a]

When ScopedTypeVariables is not enabled, it is as if your original code was written like this:

foo :: forall a. Int -> a -> [a]
foo n v = bar n
  where
    bar :: forall a. Int -> [a]
    bar n = take n $ repeat v

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 bar conflicts with the type ghci infers --- you are asserting bar has 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.

like image 69
dave4420 Avatar answered Oct 15 '22 21:10

dave4420


And just found this thread has a good explanation as well: http://www.haskell.org/pipermail/haskell-cafe/2008-June/044617.html

like image 22
Orup Avatar answered Oct 15 '22 21:10

Orup