-2

質問:「PigLatin」に翻訳するための簡単なルールは、母音で始まる単語を取り、「yay」を追加し、1つ以上の子音で始まる単語を取り、それらを後ろに転送してから「 ay」。たとえば、「able」は「ableyay」になり、「stripe」は「ipestray」になります。文字列をPig-Latin翻訳に変換する関数を記述します。

実装:

-- define function to detect vowel
isVowel :: Char -> Bool
isVowel c = elem c ['u','e','o','a','i']


-- define function Latin Pig
lp ::String -> String
lp str = if (isVowel (head str)) then do {str ++ "yay"} 
         else
            do {

                str ++ (head str)
                tail str
                lp str

                }   

問題:これまでのところ、コード(ロジック)に問題はありません。正直なところ、これはHaskell入門コースの宿題です。ただし、コンパイラはエラーを出します。

**Couldn't match expected type `t0 -> t1 -> t2 -> t3 -> [Char]'
                with actual type `Char'
    Expected type: [t0 -> t1 -> t2 -> t3 -> [Char]]
      Actual type: String
    In the first argument of `head', namely `str'
    In the second argument of `(++)', namely
      `(head str) tail str lp str'
Failed, modules loaded: none.**

私のコードの何が問題になっていますか?!

4

4 に答える 4

7

まず、パターン マッチングについて考えてみましょう。
空でないリストはx:xsとして定義でき、
x をヘッド リスト、
xsをテール リストとして 定義できます。

あなたのコードは、

-- define function Latin Pig
lp :: String -> String
lp [] = ""
lp (x:xs) = if (isVowel x) then str ++ "yay"
            else ..... -- fill here
                where str = (x:xs)   

演算子:はリストのコンストラクタであることを忘れないでください。たとえば、
'a':"bab" => "abab" のようになります。

文字列は char のリストであることに注意してください。
さらに、次のように、前の例の where 句をスキップできます。

-- define function Latin Pig
lp :: String -> String
lp [] = ""
lp str@(x:xs) = if (isVowel x) then str ++ "yay"
                else ..... -- fill here

あなたを助けるのに十分なはずです。
幸運を

于 2013-02-03T22:52:06.383 に答える
1

再帰を使用することがあなたの要件の一部であるかどうかはわかりませんが、ここにあなたの仕事に対する私の見解があります。do目的を達成するためにモナドを使用する必要はありません(それが割り当ての目的でない限り)。

if elseブロックの代わりに、パターンマッチングとガードの使用を検討することをお勧めします。

また、zurglが言ったように、次のように文字列を一致させることを利用できます。これにより、頭と尾string@(x:xs)を使用しながら、文字列全体で作業を行うことができます。xxs

注:すべての文字列はリストです。

これが私が提案したことの簡単な例です。

-- define function to detect vowel
isNotVowel :: Char -> Bool
isNotVowel c = notElem c ['u','e','o','a','i']

-- define function Latin Pig
lp :: String -> String
lp [] = []
lp p@(x:xs)
    | not $ isNotVowel x = p++"yay"
    | otherwise = let (constants, rest) = span isNotVowel p
                    in (rest++constants++"ay")

Haskellを楽しんでください!

haskellを学ぶためのいくつかの素晴らしいリソース:

于 2013-02-04T06:11:29.940 に答える