Vik*_*ahl 5 haskell types type-inference strong-typing
我正在Haskell中编写一个函数,ListLike用任何Ord元素制作直方图:
import qualified Data.ListLike as LL
...
frequencies :: (Ord x, LL.ListLike xs x) => xs -> [(x, Int)]
frequencies xs = LL.map (\x->(LL.head x, LL.length x)) $ LL.group $ LL.sort xs
Run Code Online (Sandbox Code Playgroud)
在尝试编译上面的代码时,我收到有关模糊类型的错误消息:
Ambiguous type variable `full0' in the constraint:
(LL.ListLike full0 xs) arising from a use of `LL.group'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: LL.group
In the second argument of `($)', namely `LL.group $ LL.sort xs'
In the expression:
LL.map (\ x -> (LL.head x, LL.length x)) $ LL.group $ LL.sort xs
Run Code Online (Sandbox Code Playgroud)
LL.group具有与普通列表(ListLike full0 full, ListLike full item, Eq item) => full -> full0相对应的类型(Eq a) => [a]->[[a]].
我不明白为什么有一个ambigious类型的问题.Haskell是否无法推断出存在"ListLike with fullas elements" 这样的类型,即full0?
Haskell是否无法推断出存在"ListLike with
fullas elements" 这样的类型,即full0?
不,问题是有太多类型可供选择full0,Haskell编译器不知道使用哪个.想想看:在一般情况下,可以有不止一种类型full0是一种类似列表的类型与full作为元素:[full]或Data.Sequence.Seq full或许多其他的选择.而且由于定义的通用性LL.map,full0是不受限的是[full]从函数的返回类型frequencies.
如果要限制full0为[full],则执行此操作的一种方法是使用普通旧的列表替换LL.map定义.frequenciesmap