在Haskell中检测Pig-Latin(Detecting Pig-Latin In Haskell)
我试图写一个函数来做到这一点,但不能让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"I've tried to write a function to do this but can't get GHCI to understand my code. I'm coming from an OOP background so functional programming is completely new territory for me.
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"最满意答案
这里有几个问题:
你的函数的类型是String -> String ,所以它应该只有一个参数,而你的定义有两个参数, sentence和(x:xs) 。 不要使用"true"和"false"等字符串。 使用布尔值。 这就是他们的目的。 一个if的条件必须是一个布尔值。 如果您想要保留几个条件,请使用(&&)或and来合并它们。 if -expression必须同时具有then和else 。 你可以想象if x then y else z像三元x ? y : z x ? y : z运算符在一些其他语言中。 '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" ]Several issues here:
The type of your function is String -> String, so it should only have one argument, while your definition has two arguments, sentence and (x:xs). Don't use strings like "true" and "false". Use booleans. That's what they're for. The condition of an if must be a boolean. If you want several conditions to hold, use (&&) or and to combine them. An if-expression must have both a then and an else. You can think of if x then y else z like the ternary x ? y : z operator in some other languages. 'a' and 'y' have type Char, so you can't compare them against strings with ==. Compare with "a" and "y" instead.However, there is no point in writing if something then True else False. Instead, just use the boolean expression directly.
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" ]更多推荐
发布评论