首页 > 解决方案 > 列表的“最大”功能是否仅在单独的功能中起作用?

问题描述

当我在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在上面运行,它给了我以下错误输出:listmode listghci

<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

mode在上面运行list> mode' mode listin ghci,我得到了5没有错误的预期输出。

谁能解释为什么会这样?

标签: listhaskell

解决方案


仔细看看中的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])。


推荐阅读