list - 列表的 'maximum' 函数是否只能在单独的函数中工作?

标签 list haskell

当我在代码的不同部分移动 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 listghci中运行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 函数拆分为 modemode' (使用 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/

相关文章:

database - 如何在 haskell 中使用 HDBC 有效地检查条目是否存在?

c# - 从字符串中读取字符并计算每个字符

c# - 应用 Dijkstra 算法实现时列表中的对象被删除

python - 如何使用 filter() 从包含字符串和数字的列表中删除所有字符串?

R - 将列表类型的列转换为 str 类型

python随机洗牌while循环

haskell - Haskell中Bottom的概念

haskell - Int 在 Haskell 中是如何定义的?

haskell - 对 Haskell 字符串中发现的 unicode 文字进行转义

haskell - 如何在 IHP 表单中传递 List 参数?