【发布时间】:2011-05-10 00:53:59
【问题描述】:
我经常听到这句话,守卫只是 if-then-else(或 case 语句)的语法糖。
有人可以为以下实例脱糖吗:
halfOf :: Int -> Int
halfOf x | even x = div x 2
(函数故意偏)
谢谢,
【问题讨论】:
标签: haskell syntax syntactic-sugar guard
我经常听到这句话,守卫只是 if-then-else(或 case 语句)的语法糖。
有人可以为以下实例脱糖吗:
halfOf :: Int -> Int
halfOf x | even x = div x 2
(函数故意偏)
谢谢,
【问题讨论】:
标签: haskell syntax syntactic-sugar guard
模式匹配的语义在标准的以下部分定义:Formal Semantics of Pattern Matching。
与您的问题相关的步骤是 c。如您所见,模式与表单的守卫匹配
case v of { p | g1 -> e1 ; ...
| gn -> en where { decls }
_ -> e' }
被翻译为没有保护的模式匹配:
case e' of
{y ->
case v of {
p -> let { decls } in
if g1 then e1 ... else if gn then en else y ;
_ -> y }}
因此,模式防护是根据if 定义的,“fallthrough”是通过将表达式绑定到变量来实现的,然后在if 的else 子句中重复一次,然后在您使用的模式中会失败的。
如果没有案例可以通过(如您的示例),则步骤 b 将插入一个案例,该步骤将插入默认案例 _ -> error "No match"
【讨论】:
halfOf x =
if even x
then div x 2
else error "Incomplete pattern match"
由未处理的情况触发的确切错误类型未由语言定义指定,并且因编译器而异。
编辑:如果有多个警卫和/或模式,每个警卫或模式匹配进入前一个案例的非匹配部分。
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
【讨论】: