gpt4 book ai didi

f# - 如何有效地模式匹配?

转载 作者:行者123 更新时间:2023-12-04 23:25:25 25 4
gpt4 key购买 nike

我想将整数数组与以下伪模式匹配:
哪里a表示这些数字等于或 0(即假设任何数字“等于”0)

[| a; a; a; a; a; |]          // matches [| 1; 1; 0; 0; 1 |]
[| a; a; a; not a; a; |] // matches [| 3; 3; 0; 2; 3 |]
[| a; a; not a; a; a; |] // matches [| 4; 4; 2; 0; 4 |]
[| a; not a; a; a; not a; |] // matches [| 1; 2; 0; 0; 3 |]
[| a; a; a; not a; a; |] // matches [| 1; 1; 0; 4; 1 |]
[| not a; a; a; a; a; |] // matches [| 5; 1; 0; 1; 1 |]

我该怎么做呢?

最佳答案

在您的示例中,数组的第一个元素始终是 a你可以匹配一个 bool 数组:

match Array.map (fun x -> x = Array.get arr 0 || x = 0) arr with
| [| true; true; true; true; true; |] -> ... // matches [| 1; 1; 0; 0; 1 |]
| [| true; true; true; false; true; |] -> ... // matches [| 3; 3; 0; 2; 3 |]
| [| true; true; false; true; true; |] -> ... // matches [| 4; 4; 2; 0; 4 |]
| [| true; false; true; true; false; |] -> ... // matches [| 1; 2; 0; 0; 3 |]
| [| true; true; true; false; true; |] -> ... // matches [| 1; 1; 0; 4; 1 |]
| _ -> ...

这将创建一个临时数组,但对于小尺寸的数组来说并不是什么大问题。

更新:

如果第一个 a在另一列中,您只需在该列上进行投影并进行另一个模式匹配(5 列最多有 5 个匹配项)。
match Array.map (fun x -> x = Array.get arr 1 || x = 0) arr with
| [| false; true; true; true; true; |] -> ... // matches [| 5; 1; 0; 1; 1 |]
| ...

也就是说,当伪模式的数量和复杂性增加时,最好使用函数而不是模式匹配。

关于f# - 如何有效地模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13878782/

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