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

This seventh line is a little weird:

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

What it says is:

  1. Take the function given by

    ((filter (== head ys) ys):xs)
    
  2. and call it with the argument

    (filter (/= head ys) ys)
    

which is probably not at all what you intended. This becomes more clear if you replace the expressions with names, like the following equivalent expression:

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

Did you miss to put something between the two expressions? Keep in mind that arg in this case is [a] while func is [[a]]. I think you meant to say

func : [arg]

but I'm not sure, because I don't know what you are trying to accomplish.

于 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)ただし、 typeの値を返すため、typeを((filter (== head ys) ys):xs)持ち、 typeの の前に追加されます。[[a]]filter (== head ys) ys[a]xs[[a]]

の期待される戻り値はpack'何ですか? その動作を示す例を挙げていただけますか?

于 2013-09-04T15:26:16.490 に答える