Pergunta

I'm wondering if a list is a prefix of a second list, using the following code:

prefix :: [a] -> [b] -> Bool
prefix [] _ = True
prefix _ [] = False
prefix (x:xs) (y:ys) = if (x==y) then prefix xs ys else False

But it returns an error:

Inferred type is not general enough
*** Expression    : prefix
*** Expected type : [a] -> [b] -> Bool
*** Inferred type : [a] -> [a] -> Bool

Can someone help me get this to work?

Foi útil?

Solução

Your type signature claims the two lists can have different types, but they can't. So the compiler complains that it inferred a type that was less general than the one you asked for.

Outras dicas

That's because you're comparing the types you've named a and b using (x==y). Checking the type of ==, that means they are the same type, which has an equality test:

Prelude> :t (==)
(==) :: Eq a => a -> a -> Bool

So the type signature that is inferred is actually Eq a => [a] -> [a] -> Bool.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top