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)
这里有几个问题:
String -> String,所以它应该只有一个参数,而你的定义有两个参数,sentence和(x:xs)."true"和的字符串"false".使用布尔值.这就是他们的目的.if必须是布尔值的条件.如果您想要保留多个条件,请使用(&&)或and组合它们.if必须同时包含a then和a else.您可以将if x then y else 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"
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |