Pergunta

Esta pergunta foi inspirada por isso responda Para outra pergunta, indicando que você pode remover todas as ocorrências de um elemento de uma lista usando uma função definida como:

removeall = filter . (/=)

Trabalhando com lápis e papel dos tipos de filter, (/=) e (.), a função tem um tipo de

removeall :: (Eq a) => a -> [a] -> [a]

que é exatamente o que você esperaria com base no contrato. No entanto, com GHCI 6.6, eu entendo

gchi> :t removeall
removeall :: Integer -> [Integer] -> [Integer]

A menos que eu especifique o tipo explicitamente (nesse caso, funciona bem). Por que Haskell está inferindo um tipo tão específico para a função?

Foi útil?

Solução

Why is Haskell inferring such a specific type for the function?

GHCi is using type defaulting, to infer a more specific type from a set of possibles. You can avoid this easily by disabling the monomorphism restriction,

Prelude> :set -XNoMonomorphismRestriction
Prelude> let removeall = filter . (/=)
Prelude> :t removeall 
removeall :: (Eq a) => a -> [a] -> [a]

Outras dicas

It is also worth noting that if you don't assign a name to the expression, typechecker seems to avoid type defaulting:

Prelude> :t filter . (/=)
filter . (/=) :: (Eq a) => a -> [a] -> [a]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top