"bar" | _ -> "baz"-6ren">
gpt4 book ai didi

pattern-matching - OCaml 模式与非常量匹配

转载 作者:行者123 更新时间:2023-12-04 22:06:58 24 4
gpt4 key购买 nike

是否可以对变量而不是常量值进行模式匹配:

# let x = 2 in
let y = 5 in
match 2 with
| x -> "foo"
| y -> "bar"
| _ -> "baz";;
let y = 5 in
Warning 26: unused variable y.
let x = 2 in
Warning 26: unused variable x.
| y -> "bar"
Warning 11: this match case is unused.
| _ -> "baz";;
Warning 11: this match case is unused.
- : string = "foo"

显然,使用这种语法, x -> "foo" 案例包含所有内容。有没有办法让它等同于:
match 2 with
| 2 -> "foo"
| 5 -> "bar"
| _ -> "baz"

在运行时确定匹配表达式的值在哪里?

最佳答案

你需要 when 守卫:

let x = 2 in
let y = 5 in
match 2 with
| z when z = x -> "foo"
| z when z = y -> "bar"
| _ -> "baz";;

错误消息非常有指导意义。当您使用:
let x = 2 in
...
match 2 with
| x -> "foo"
| ...

新值 x 遮蔽了先前 let-bound 中的值 x 因此是第一条错误消息。此外,由于新的 x 匹配所有内容,因此以下两个 y_ 模式显然是多余的。

请注意,匹配常量 ( match 2 with ) 不是一个好主意。

关于pattern-matching - OCaml 模式与非常量匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10435572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com