2013-02-03 83 views
-1

問題:翻譯成「豬拉丁文」的簡單規則是取一個以元音開頭並添加「yay」的單詞,同時接受任何與一個或多個輔音開頭並轉移的單詞他們在追加「唉」之前到後面。例如,「有能力」變成「可以」,「條帶」變成「可以」。編寫一個函數,將字符串轉換爲它的Pig-Latin翻譯。Haskell:豬拉丁文

實現:

-- 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.** 

我的代碼有什麼問題?

+5

'do'-notation是單子,我真的懷疑你*想要*在這裏使用List monad。 –

+4

查理,我認爲你的問題在於你不懂基本的haskell語法。不要只是一個C程序,對它進行一些基本的轉換,並期望結果在Haskell中工作。 – Cubic

回答

6

首先,考慮模式匹配。
任何不空單可被定義爲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 [email protected](x:xs) = if (isVowel x) then str ++ "yay" 
       else ..... -- fill here 

應該足以幫助你。
祝你好運

1

我不確定這是否是你的要求的一部分使用遞歸,但這裏是我對你的任務。你不需要使用monad來實現你想要的(除非這是分配的目標?)。

您可能想考慮使用模式匹配和守衛而不是if else塊。

此外,像zurgl說,你可以採取這樣的字符串相匹配的優勢:[email protected](x:xs)這將使您能夠對整個字符串的工作,同時還使用了頭x和尾部xs

注意:所有字符串都是列表。

這是我建議的一個簡單例子。

-- 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 [email protected](x:xs) 
    | not $ isNotVowel x = p++"yay" 
    | otherwise = let (constants, rest) = span isNotVowel p 
        in (rest++constants++"ay") 

玩得開心學習哈斯克爾!

學習Haskell的一些不錯的資源:

1

這裏是把豬拉丁規則的另一種方式:

  • 如果一個字沒有按」從一系列輔音開始,那麼翻譯就是其後的原始單詞「耶」
  • 否則翻譯這個詞的其餘部分,其次是輔音的初始運行,其次是「AY」

這種情況很容易轉化爲哈斯克爾。

(實際Haskell代碼省略掉,因爲這是家庭作業。)

你會發現它有助於你的isVowel函數從該Data.List模塊功能break結合。