Ocaml模式匹配:为什么不使用此匹配?

问题描述 投票:-1回答:2

我刚刚设计了一个无用的功能:

let rec f = fun x y-> 
    let tmp = f (x-1) y in (match tmp with | y->y|m->m);;

为什么m->m未使用匹配?为什么这里的y->y实际上是一个通配符,而不是参数y的值?我想做的是如下:

let rec f = fun x y ->
    let tmp = f (x-1) y in if tmp=y then y else tmp;;

为什么模式匹配不起作用?作为回答,请解决问题,而不是建议采取必要的方法。谢谢!

pattern-matching ocaml
2个回答
3
投票

y中的match tmp with y -> y | m -> m是一个(新的)变量。因此它匹配任何值。

尝试评估此表达式:

(fun x -> match x with y -> y + 1 | w -> w + 2) 3;;

结果是4x在应用函数时与3绑定; 3与变量y匹配;最后,子表达式y + 1[ x = 3; y = 3]的上下文中评估为4。

子表达式if tmp=y then y else tmp相当于简单的tmp

为什么要在整数上进行模式匹配?你的功能应该是什么?


-1
投票

使用when来克服它。

let rec f = fun x y-> 
    let tmp = f (x-1) y in (match tmp with |_ when tmp = y->y|m->m);;
© www.soinside.com 2019 - 2024. All rights reserved.