guards 御林军

发布时间 2023-04-06 11:44:57作者: 牧羊龟

根据BMI获得不同的输出,如下

bmiTell :: ( RealFloat a ) => a -> String
bmiTell bmi
  | bmi <= 18.5 = "underweight"
  | bmi <= 25.0 = "normal"
  | bmi <= 30.0 = "fat" 
  | otherwise = "whale!"
  • 御林军由函数名及其参数后面的竖条表示。它们通常是缩进的对齐的
  • 御林军是一个布尔表达式。如果求值为True,则执行对应的函数体。如果求值为False,则检查下一次,以此类推
  • 很多时候,最后的御林军是otherwise,otherwise被简单的定义为otherwise = True
  • 模式匹配只在满足输入模式时匹配,而御林军检查布尔条件
  • 如果一个函数的所有保存都被求值为False,并且没有给出otherwise,则计算失败并继续到下一个模式,如果没有可接受的模式或御林军,则会抛出error
  • 注意,在第参数之后,一次判断之前,没有=

任意数量参数的函数都可以使用御林军,如下

bmiTell :: ( RealFloat a ) => a -> String
bmiTell weight height
  | weight / height ^ 2 <= 18.5 = "underweight"
  | weight / height ^ 2 <= 25.0 = "normal"
  | weight / height ^ 2 <= 30.0 = "fat" 
  | otherwise = "whale!"