跳到主要内容

条件语句

if ... then ... else ...

describeNumber :: Int -> String
describeNumber x = if x > 0
then "Positive"
else if x < 0
then "Negative"
else "Zero"

case ... of ...

支持模式匹配

describeOddEven :: Int -> String
describeOddEven n = case n `mod` 2 of
0 -> "Even"
1 -> "Odd"
_ -> "This shouldn't happen for integers!"

guard

if ... then ... else ... 的扩展

otherwise并不属于guard语法,而是True的绑定(也就是说otherwise就是True

describeNumber :: Int -> String
describeNumber x
| x > 0 = "Positive"
| x < 0 = "Negative"
| otherwise = "Zero"

举个例子

-- 混合使用三种语法

-- 定义不同的电影类型
data MovieType = Standard | ThreeD | IMAX

-- 定义不同的零食选项
data Snack = Popcorn | Soda | Combo

-- 计算电影和零食的总价
calculatePrice :: MovieType -> Maybe Snack -> Int
calculatePrice movieType snackOption = moviePrice + snackPrice
where
-- 根据电影类型计算电影票价
moviePrice = case movieType of
Standard -> 10 -- 标准电影票价为10
ThreeD -> 15 -- 3D电影票价为15
IMAX -> 20 -- IMAX电影票价为20

-- 根据零食选项计算零食价格
snackPrice
| Just Popcorn <- snackOption = 5 -- 爆米花价格为5
| Just Soda <- snackOption = 3 -- 汽水价格为3
| Just Combo <- snackOption =
if movieType == IMAX
then 5 -- 如果选择IMAX电影,套餐价格为5
else 7 -- 其他电影类型,套餐价格为7
| otherwise = 0 -- 没有选择零食,价格为0