Function cannot match type

I have a function as shown below:

foo :: Int -> a -> [a] foo nv = 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 deleting a type declaration in a bar, the code can be compiled without errors. So what is a bar type declaration here? And why does an error occur because the declaration of type bar is more general than the definition of bar (which is bound to some type in foo)?

Thanks for any help!

+6
source share
2 answers

a in

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

and a in

  bar :: Int -> [a] 

- different type variables with the same name.

To get the expected behavior, enable the ScopedTypeVariables extension (for example, by inserting {-# LANGUAGE ScopedTypeVariables #-} at the beginning of the source file) and change the signature of type foo to

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

When ScopedTypeVariables is not enabled, it looks like your source code was written as follows:

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

It is not true that ghci implicitly uses ScopedTypeVariables unless you specify type annotation for bar .

Instead, the type annotation you specify for bar conflicts with the ghci infers type --- you say that bar has a type that ghci knows that it cannot have.

When you delete a type annotation, you delete the conflict.

ScopedTypeVariables changes the value of the type annotations that you supply. This does not affect the ghc type.

+9
source

And the stream just found has a good explanation: http://www.haskell.org/pipermail/haskell-cafe/2008-June/044617.html

+2
source

Source: https://habr.com/ru/post/916395/


All Articles