在Haskell中检测Pig-Latin

rex*_*lia 1 haskell functional-programming

我曾尝试编写一个函数来执行此操作,但无法让GHCI理解我的代码.我来自OOP背景,所以函数式编程对我来说是一个全新的领域.

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"
Run Code Online (Sandbox Code Playgroud)

ham*_*mar 5

这里有几个问题:

  1. 你的函数的类型是String -> String,所以它应该只有一个参数,而你的定义有两个参数,sentence(x:xs).
  2. 不要使用像"true"和的字符串"false".使用布尔值.这就是他们的目的.
  3. 一个if必须是布尔值的条件.如果您想要保留多个条件,请使用(&&)and组合它们.
  4. 表达式if必须同时包含a then和a else.您可以将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"
                      ]
Run Code Online (Sandbox Code Playgroud)