col*_*ang 4 f# pattern-matching
我想将一个整数数组与以下伪模式匹配:其中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 |]
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
在您的示例中,数组的第一个元素始终a可以匹配布尔数组:
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 |]
| _ -> ...
Run Code Online (Sandbox Code Playgroud)
这将创建一个临时数组,但对于小尺寸的数组来说并不是什么大问题.
更新:
如果第一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 |]
| ...
Run Code Online (Sandbox Code Playgroud)
也就是说,当伪模式的数量和复杂性增加时,最好使用函数而不是模式匹配.
| 归档时间: |
|
| 查看次数: |
281 次 |
| 最近记录: |