当我在代码的不同部分移动 Data.List maximum
函数时,我无法理解 Haskell 的错误。我使用一些内置函数来查找任意整数列表的众数。例如,当给定 mode
列表时 list = [1,2,3,4,5,5,6,6,5,5,4,4,3,4, 5,6,7,8,6,5,3,2,5]
,它应该返回5
。
当我将内置 maximum
函数放入 mode
函数中时,如下所示:
mode l = case l of
[] -> []
(x : xs) ->
let x = map length (group (sort l))
y = map head (group (sort l))
in snd (maximum (zip x y)) --<-----<-----<-- This Line
我在上面的list
上使用命令> mode list
在ghci
中运行mode
,它给出了我的错误输出如下:
<interactive>:2:7: error:
* Couldn't match type `Integer' with `[a]'
Expected type: [[a]]
Actual type: [Integer]
* In the first argument of mode', namely `list'
In the expression: mode' list
In an equation for `it': it = mode' list
* Relevant bindings include it :: [a] (bound at <interactive>:2:1)
但是,当我将 mode
函数拆分为 mode
和 mode'
(使用 mode'
执行最大)像这样:
mode' f l = snd (maximum (f l)) --<-----<-----<-- Now Here
mode l = case l of
[] -> []
(x : xs) ->
let x = map length (group (sort l))
y = map head (group (sort l))
in zip x y
我在上面的list
上运行mode
,并在ghci
中使用>mode'模式列表
,我得到5
的预期输出没有错误。
谁能解释一下为什么会这样?
最佳答案
仔细看看 mode
下的 case
语句:
在您的工作示例中:
mode l = case l of
[] -> []
(x : xs) -> let ... in zip x y
mode
的返回类型是一个列表。在损坏的版本中:
mode l = case l of
[] -> []
(x : xs) -> let ... in snd (maximum (zip x y))
第一个分支中的返回类型是列表,但在第二个分支中它是一个 Integer
(如 zip x y::[(Integer, a)]
) 。这是一个类型错误。
在工作情况下,mode
的另一个分支返回一个列表,因此类型有效:mode::(Num a, Ord b) => [b] -> [(a, b)]
和 mode'
类型检查。
错误消息 Couldn't match type 'Integer' with '[a]'
表示该函数需要一个列表 [a]
,但却得到一个 Integer
:你的列表包含整数,所以你可以知道该函数期望参数是列表的列表:那么类型是有效的(mode::Ord a => [[ a]] -> [a]
)。
关于list - 列表的 'maximum' 函数是否只能在单独的函数中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53998121/