haskell - Haskell 中 if 语句的正确语法

标签 haskell if-statement

您唯一需要的输入是您获得的成绩编号。这就是我到目前为止所拥有的。

myScore x = if x > 90
    then let x = "You got a A"
if 80 < x < 90 
    then let x = "you got a B"
if 70 < x < 80
    then let x = "You got a C"
if 60 < x < 90
    then let x = "you got a D"
else let x = "You got a F"

这给了我一个错误“输入`if'时解析错误”,我也尝试过:

myScore x = (if x > 90 then "You got an A" | if 80 < x < 90 then "You got a B" | if 70 < x < 80 then "You got a D" | if 60 < x < 70 then "You got a D"  else "You got a F")

但这也不起作用。

最佳答案

你不能拥有 let在条件语句内,否则变量 x在需要它的以下表达式中将不可用。

在你的情况下,你甚至不需要 let 绑定(bind),因为你只想立即返回字符串,所以你可以这样做:

myScore x = 
    if x > 90 then "You got a A"
    else if 80 < x && x < 90 then "you got a B"
    else if 70 < x && x < 80 then "You got a C"
    else if 60 < x && x < 70 then "you got a D"
    else "You got a F"

另请注意,您不能执行 80<x<90 - 您必须将两个表达式与 && 结合起来运算符..

使用守卫,上面的语法可以进一步简化:

myScore x
    | x > 90 = "You got a A"
    | x > 80 = "you got a B"
    | x > 70 = "You got a C"
    | x > 60 = "you got a D"
    | otherwise = "You got a F"

关于haskell - Haskell 中 if 语句的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15317895/

相关文章:

haskell - 为什么 ghci 给我的是 "1++ 2"的类型而不是 ragequitting?

ios - Swift if 语句 - 多个条件用逗号分隔?

shell - 如何否定/"reverse mean"这个搜索——也就是 "!"的意思

JavaScript:if 语句正在改变随机生成器的结果?

haskell - Emacs 中的 Goto 定义 - Haskell 模式

haskell - 如何在 Haskell 中显示有限时间的单词

javascript - 令人沮丧的语法错误

python - 分组依据 + 新列 + 根据条件抓取前行值

haskell - 函数中不一致的 do 表示法

使用代理顺序对不可排序列表进行 Haskell 排序