la función no pudo coincidir con el tipo

I have function as below:

    foo :: Int -> a -> [a]
    foo n v = bar n
        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)?

Gracias por cualquier ayuda!

preguntado el 22 de mayo de 12 a las 21:05

2 Respuestas

La a in

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

y 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 a

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
    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.

contestado el 22 de mayo de 12 a las 21:05

Thanks for help! As I said, if removing type declaration of 'bar', ghci can compile the code, does that mean ghci implicitly using ScopedTypeVariable here for it? - Orup

be more clear, scoped type variables and removing 'bar' type declaration both can make the code compiled. just wondering if they are doing the same trick. - Orup

No, they get to the same compiled code, but they get there differently. See my edit. - dave4420

Then if without scoped type variables, can we declare type of bar as what ghci infers? - Orup

And just found this thread has a good explanation as well:

contestado el 23 de mayo de 12 a las 08:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.