[英]Correct syntax for if statements in Haskell
您需要的唯一輸入是您獲得的成績編號。 這是我到目前為止。
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-binding 因為您只想立即返回字符串,所以您可以這樣做:
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"
您需要在每個if
之前添加else
。 回想一下,在 Haskell 中,每個表達式都必須計算為一個值。 這意味着每個if
表達式都必須有一個匹配的then
子句和一個匹配的else
子句。 您的代碼只有一個else
和四個if
。 編譯器抱怨因為缺少else
s。 當你修復它時,你的 Haskell 代碼看起來很像來自其他編程語言的if...else if...else
鏈。
定義x
不會在其詞法范圍之外定義它——在這種情況下, x
將無法被任何東西訪問。 相反,使用語法
let x =
if 5 < 4
then "Hmm"
else "Better"
in "Here's what x is: " ++ x
此外,使用所有這些if
s 並不是 Haskell 中的最佳方法。 相反,您可以使用保護語法:
insideText x
| elem x [2,3,7] = "Best"
| elem x [8,9,0] = "Better"
| otherwise = "Ok."
為了完整起見,這里是@hammar 建議的守衛語法:
myScore x
| x > 90 = "A"
| x > 80 = "B"
| x > 70 = "C"
| x > 60 = "D"
| otherwise = "F"
(“E”怎么樣?)
注意這里不需要檢查x > 80 && x < 90
,因為當它通過第一個守衛時,肯定是x <= 90
。 對於所有以下守衛也是如此:每當嘗試守衛時,所有前面的守衛都保證是假的。
這也糾正了邏輯錯誤,如果 x == 90 得分為“F”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.