1

我正在解决 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]]

有什么东西在我头上。有人可以解释我错过了什么吗?

4

2 回答 2

3

第七行有点奇怪:

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

它说的是:

  1. 取给定的函数

    ((filter (== head ys) ys):xs)
    
  2. 并用参数调用它

    (filter (/= head ys) ys)
    

这可能根本不是您想要的。如果将表达式替换为名称,这一点会变得更加清楚,例如以下等效表达式:

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

您是否错过了在两个表达式之间添加一些内容?请记住,arg在这种情况下是[a]while funcis [[a]]。我想你是想说

func : [arg]

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

于 2013-09-04T15:16:25.173 回答
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)有 type [[a]],因为filter (== head ys) ys返回一个 type 的值,并且它被附加到type[a]的前面。xs[[a]]

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

于 2013-09-04T15:26:16.490 回答