Haskell:类型推理和函数组合 [英] Haskell: type inference and function composition

查看:74
本文介绍了Haskell:类型推理和函数组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是由这个 $ in-haskell-using-prelude / 1335530#1335530# b $ b

  removeall = filter。 (/ =)

使用类型的铅笔和纸张进行处理过滤器(/ =)(。)

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

这正是您期望根据合约得出的结果。然而,在GHCi 6.6中,我得到

  gchi> :t removeall 
removeall :: Integer - > [整数] - >除非我明确地指定类型(在这种情况下,它可以很好地工作),否则[整型]

为什么Haskell为这个函数推断出这种特定的类型?为什么Haskell推断出这样一种特定类型的函数?特定类型的函数?

GHCi正在使用键入默认值,从一组可能值推断出更具体的类型。您可以通过禁用单态限制来轻松避免这种情况,

  Prelude> :set -XNoMonomorphismRestriction 
Prelude>让removeall = filter。 (/ =)
前奏> :t removeall
removeall ::(Eq a)=> a - > [a] - > [a]


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?

解决方案

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]

这篇关于Haskell:类型推理和函数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆