2012-03-02 83 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