2012-03-02 44 views
1

我試過編寫一個函數來做到這一點,但無法讓GHCI理解我的代碼。我來自OOP背景,所以函數式編程對我來說是一個全新的領域。在Haskell中檢測豬拉丁文

checkPigLatin :: String -> String 
checkPigLatin sentence (x:xs) 
    | check == "true" = "This is Pig Latin" 
    | otherwise = "Not Pig Latin" 
    where check = if (x `elem` "aeiouAEIOU", '-' `elem` xs, snd(break('a'==) xs) == 'a', snd(break('a'==) xs) == 'y') then "true" 
+1

什麼是你想的'if'裏面做?你似乎正在構建一個三元組:這是行不通的。 'if'後面的表達式需要評估爲'Bool'。你也錯過了'else'部分。 – 2012-03-02 20:05:11

回答

5

幾個問題在這裏:

  1. 類型的功能是String -> String,因此它應該只有一個參數,而你的定義有兩個參數,sentence(x:xs)
  2. 請勿使用像"true""false"這樣的字符串。使用布爾值。這就是他們的目的。
  3. if的條件必須是布爾值。如果您想要保留若干條件,請使用(&&)and來合併它們。
  4. if -expression必須同時具有thenelse。你可以想象if x then y else z像三元x ? y : z運算符一些其他語言。
  5. 'a''y'的類型爲Char,因此您無法將它們與==的字符串進行比較。改爲與"a""y"進行比較。

但是,寫作if something then True else False沒有意義。相反,直接使用布爾表達式。

checkPigLatin :: String -> String 
checkPigLatin (x:xs) 
    | check  = "This is Pig Latin" 
    | otherwise = "Not Pig Latin" 
    where check = and [ x `elem` "aeiouAEIOU" 
         , '-' `elem` xs 
         , snd (break ('a'==) xs) == "a" 
         , snd (break ('a'==) xs) == "y" 
         ] 
+0

「checkPigLatin」「''怎麼辦? – 2012-03-02 20:43:48

+0

@ДМИТРИЙМАЛИКОВ:是的,您可能還想爲空字符串添加一個案例。另外,我沒有檢查這是否確實做了正確的事情,我只關注語法和類型錯誤。 – hammar 2012-03-02 20:46:14

+0

非常感謝輸入的人。感謝哈馬爾指出了這個功能的所有缺陷,這真的有助於學習過程。但是,恐怕它仍然不能達到我想要的效果。例如checkPigLatin「eck-chay ig-pay atin lay」應該已經工作了。 豬拉丁文的三個基本特徵是它以一個元音開頭,它有「 - 」,以「ay」結尾。我認爲這個功能正在檢查所有這些。 Idk有什麼問題。 – rexbelia 2012-03-02 20:58:24

0

不太確定字符串檢查發生了什麼,但也許這就是你需要的。

checkPigLatin :: String -> String 
checkPigLatin [] = "Empty string" 
checkPigLatin (x:xs) 
    | check = "This is Pig Latin" 
    | otherwise = "Not Pig Latin" 
    where check = and [ x `elem` "aeiouAEIOU" 
         , '-' `elem` xs 
         , snd (break ('a' ==) xs) == "a" 
         , snd (break ('a' ==) xs) == "y" 
         ] 

而且

pisya> checkPigLatin "checkPigLatin" 
"Not Pig Latin" 
it :: String 
1

你的代碼有一些問題,但它們都很小。

  • 當你說checkPigLatin sentence (x:xs),你是說,你的函數有兩個參數:sentence(x:xs)。你的意思是說只是(x:xs)

  • 有沒有必要返回"true",這是一個String,當你可以返回True :: BoolBool已經是if內部表達式返回的類型。這意味着您根本不需要if聲明。

  • 在括號中的謂詞,您使用,爲邏輯AND,但在Haskell是&&

  • break結果是一個字符串,所以寫"a"其第二個參數,不'a'

  • 最後 - 這是關於豬拉丁語,不哈斯克爾 - 我不知道,沒有(snd(break('a'==) xs) == "a")是要保證自己是不是豬拉丁

希望這有助於,歡迎!

編輯:
下面是更新後的代碼,如果你喜歡它:

checkPigLatin :: String -> String 
checkPigLatin (x:xs) 
    | check = "This is Pig Latin" 
    | otherwise = "Not Pig Latin" 
    where check = (x `elem` "aeiouAEIOU") && 
        ('-' `elem` xs) && 
        (snd(break('a'==) xs) == "a") && 
        (snd(break('a'==) xs) == "y") 
+0

謝謝。第二個snd(break())應該是(snd(break('y'==)xs)==「y」)對不對?我知道這不能保證某些東西不是豬拉丁文,但它應該是豬拉丁文,它不會失敗吧?你有沒有別的選擇? – rexbelia 2012-03-02 23:01:02