gpt4 book ai didi

haskell - 没有因使用 ‘mymerge’ 而产生 (Ord a0) 的实例

转载 作者:行者123 更新时间:2023-12-02 16:57:52 26 4
gpt4 key购买 nike

我正在学习“Haskell 编程”,我正在尝试合并两个已排序的列表。这是我的代码:

mymerge :: Ord a => [a] -> [a] -> [a]
mymerge xs [] = xs
mymerge [] ys = ys
mymerge (x:xs) (y:ys) | x < y = x : mymerge xs (y:ys)
| otherwise = y : mymerge (x:xs) ys

它适用于所有情况,除了当我尝试将测试定义为:

t72 = mymerge [] []

错误是:

No instance for (Ord a0) arising from a use of ‘mymerge’
The type variable ‘a0’ is ambiguous
Relevant bindings include t72 :: [a0] (bound at ch06.hs:109:1)
Note: there are several potential instances:
instance (Ord a, Ord b) => Ord (Either a b)
-- Defined in ‘Data.Either’
instance forall (k :: BOX) (s :: k). Ord (Data.Proxy.Proxy s)
-- Defined in ‘Data.Proxy’
instance (GHC.Arr.Ix i, Ord e) => Ord (GHC.Arr.Array i e)
-- Defined in ‘GHC.Arr’
...plus 26 others
In the expression: mymerge [] []
In an equation for ‘t72’: t72 = mymerge [] []

我怀疑它试图告诉我没有足够的信息来推断 [] 的类型。如果我明确定义函数的类型,它就会起作用:

t72 :: Ord a => [a]
t72 = mymerge [] []

这是使其正常工作的惯用方法吗?

更新:我不会按照建议将其标记为重复项,另一个问题的答案没有提及单态性限制。

最佳答案

这不是臭名昭著的monomorphism restriction吗? ?在 GHCi 8.0.1 中,这可以按预期工作,无需注释:

Prelude> :t mymerge [] []
mymerge [] [] :: Ord a => [a]

因为:

Prelude> :showi language
base language is: Haskell2010
with the following modifiers:
-XNoDatatypeContexts
-XExtendedDefaultRules
-XNoMonomorphismRestriction
-XNondecreasingIndentation

所以这也有效:

{-# LANGUAGE NoMonomorphismRestriction #-}

mymerge :: Ord a => [a] -> [a] -> [a]
mymerge xs [] = xs
mymerge [] ys = ys
mymerge (x:xs) (y:ys) | x < y = x : mymerge xs (y:ys)
| otherwise = y : mymerge (x:xs) ys

t72 = mymerge [] []

简而言之,默认情况下,t72 的类型将被推断为比您预期的多态性更少。

关于haskell - 没有因使用 ‘mymerge’ 而产生 (Ord a0) 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41205322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com