无法匹配Pack函数中的预期类型

时间:2013-09-04 14:58:23

标签: haskell

我正在解决Haskell中的99个问题并遇到一个我无法解决的类型问题。我在第一次尝试时使用了包装函数来解决问题。

目标

将列表元素的连续副本打包到子列表中。如果列表包含重复的元素,则应将它们放在单独的子列表中。

实施例

Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']
["aaaa","b","cc","aa","d","eeee"]

我的代码:

pack :: (Eq(a)) => [a] -> [[a]]
pack [] = []
pack xs = pack' ((filter (== head xs) xs):[]) (filter (/= head xs) xs)

pack' :: (Eq(a)) => [[a]] -> [a] -> [[a]]
pack' xs [] = xs
pack' xs ys = ((filter (== head ys) ys):xs) (filter (/= head ys) ys)

所以当我运行它时,我遇到第7行的问题并得到以下调试器输出:

09.hs:7:15:
    Couldn't match expected type `[a0] -> [[a]]'
                 with actual type `[[a]]'
    The function `(filter (== head ys) ys) : xs'
    is applied to one argument,
    but its type `[[a]]' has none
    In the expression: ((filter (== head ys) ys) : xs) (filter (/= head ys) ys)
    In an equation for pack':
        pack' xs ys = ((filter (== head ys) ys) : xs) (filter (/= head ys) ys)
Failed, modules loaded: none.

我只是看不到额外的[a0] - > [[a]]来自。

Prelude> let b = [5,3,4,5,3,2,3,4,5,6]
Prelude> (filter (== head b) b):[]
[[5,5,5]]
Prelude> (filter (== head b) b):[[4,4]]
[[5,5,5],[4,4]]

有些东西在我头上。有人可以解释我错过的东西吗?

2 个答案:

答案 0 :(得分:3)

这第七行有点奇怪:

((filter (== head ys) ys):xs) (filter (/= head ys) ys)

它说的是:

  1. 采用

    给出的功能
    ((filter (== head ys) ys):xs)
    
  2. 并使用参数

    调用它
    (filter (/= head ys) ys)
    
  3. 这可能完全不是你想要的。如果用名称替换表达式,则会变得更加清晰,如下面的等效表达式:

    let func = ((filter (== head ys) ys):xs)
        arg  = (filter (/= head ys) ys)
    in  func arg
    

    您是否错过了在两个表达式之间添加内容?请注意,arg在这种情况下为[a]func[[a]]。我想你想说

    func : [arg]
    

    但我不确定,因为我不知道你想要完成什么。

答案 1 :(得分:1)

表达式pack' xs ys = ((filter (== head ys) ys):xs) (filter (/= head ys) ys)包含错误。子表达式((filter (== head ys) ys):xs)用作(filter (/= head ys) ys)作为参数的函数。但是,((filter (== head ys) ys):xs)的类型为[[a]],因为filter (== head ys) ys会返回[a]类型的值,并且会将其附加到xs的前面,这是类型[[a]]

pack'的预期回报值是多少?你能提供一个证明其行为的例子吗?