list - 列表的“最大”功能是否仅在单独的功能中起作用?
问题描述
当我在Data.List maximum
代码的不同部分移动函数时,我无法理解 Haskell 的错误。我正在使用一些内置函数来查找任意整数列表的模式。例如,当mode
给出 list时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
我使用命令 > inmode
在上面运行,它给了我以下错误输出:list
mode list
ghci
<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
我mode
在上面运行list
> mode' mode list
in ghci
,我得到了5
没有错误的预期输出。
谁能解释为什么会这样?
解决方案
仔细看看中的case
声明mode
:
在您的工作示例中:
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
(as 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]
)。
推荐阅读
- python - 在 Python 中使用 MNIST FASHION 为图像分类准备/渲染图像
- google-apps-script - 谷歌应用脚本根据可变列组的数量插入多行(由谷歌表单生成)
- performance - 有条件地在通道管道中附加 HttpObjectAggregator
- c - 在 fps 多人游戏中如何处理摄像机视图?
- tensorflow - 如何获取 inter_op 线程号。在 TensorFlow Op 内核中
- java - Eclipse 快速修复显示没有可用的建议
- numpy - 重塑迁移学习
- reactjs - 如何在某个集合中添加字段?
- java - 为什么我不必使用匿名类的覆盖方法,而是只使用它的对象来达到覆盖方法?
- android - 使用 Datastore 防止内存泄漏的最佳做法是什么?