Haskell: type inference and function composition

好久不见. 提交于 2019-12-18 12:56:12

问题


This question was inspired by this answer to another question, indicating that you can remove every occurrence of an element from a list using a function defined as:

removeall = filter . (/=)

Working it out with pencil and paper from the types of filter, (/=) and (.), the function has a type of

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

which is exactly what you'd expect based on its contract. However, with GHCi 6.6, I get

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

unless I specify the type explicitly (in which case it works fine). Why is Haskell inferring such a specific type for the function?


回答1:


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]



回答2:


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]


来源:https://stackoverflow.com/questions/1344414/haskell-type-inference-and-function-composition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!