我经常听到这句话,守卫只是 if-then-else(或 case 语句)的语法糖。
有人可以对以下实例进行脱糖:
halfOf :: Int -> Int
halfOf x | even x = div x 2
(该功能是有意偏向的)
谢谢,
最佳答案
halfOf x =
if even x
then div x 2
else error "Incomplete pattern match"
语言定义未指定由未处理案例触发的确切错误类型,并且因编译器而异。
编辑 :如果有多个 guard 和/或模式,每个 guard 或模式匹配进入前一个案例的非匹配部分。
compare x y
| x == y = foo
| x /= y = bar
compare _ _ = baz
生产
compare x y =
if x == y
then foo
else if x /= y
then bar
else baz
关于haskell - 保护脱糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181261/