简体   繁体   English

我正在尝试使用 haskell 中的警卫进行分类

[英]I'm trying to classify using guards in haskell

classify n: returns a letter grade based upon a numeric grade, according to the following schema:分类 n:根据以下模式返回基于数字等级的字母等级:

  • if n ≥ 90, return 'A'如果 n ≥ 90,则返回 'A'
  • if 89 ≤ n ≤ 70, return 'B'如果 89 ≤ n ≤ 70,则返回 'B'
  • if 69 ≤ n ≤ 50, return 'C'如果 69 ≤ n ≤ 50,则返回 'C'
  • otherwise, return 'D'.否则,返回“D”。

this is my haskell code:这是我的 haskell 代码:

classify n
       | n => 90 = 'A'
       | 89 <= n <= 70 = 'B'
       | 69 <= n <= 50 = 'C'
       | otherwise = 'D' 

but it keeps giving me errors但它一直给我错误

For greater than or equal, >= is used, not => , furthermore you can not chain conditions like in Python, you thus should work with 89 >= n && n >= 70 :对于大于或等于,使用>=而不是=> ,此外,您不能像 Python 中那样链接条件,因此您应该使用89 >= n && n >= 70

classify n
    | n >= 90 = 'A'
    | 89 >= n && n >= 70 = 'B'
    | 69 >= n && n >= 50 = 'C'
    | otherwise = 'D' 

You can simplify the expression to:您可以将表达式简化为:

classify n
    | n >= 90 = 'A'
    | n >= 70 = 'B'
    | n >= 50 = 'C'
    | otherwise = 'D' 

this works for integers because the guard n >= 90 will fire for all values greater than or equal to 90. This thus means that no such values will be evaluated for the next guards and only integers less than or equal to 89 will be evaluated by the other guards.这适用于整数,因为守卫n >= 90将对所有大于或等于 90 的值触发。因此,这意味着不会为下一个守卫评估此类值,并且只会评估小于或等于 89 的整数其他守卫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM