在Haskell中检测Pig

编程入门 行业动态 更新时间:2024-10-22 20:34:17
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" ]

更多推荐

本文发布于:2023-08-01 16:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1361454.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Haskell   Pig

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!