Ono*_*cci 3 f# pattern-matching
F#中有多个实例模式吗?
考虑一下我正在制作一份清单.我有以下模式匹配
match l with
| [] | [_] -> l //if the list is empty or contains only one item, simply return it
|
//is there a pattern to test if all of the elements are identical?
Run Code Online (Sandbox Code Playgroud)
换句话说,传递[]或[1]应该只返回列表,所以应该[1; 1; 1; ...],但我无法弄清楚如何模式匹配最后一个模式.这可能吗?或者我有可能使用更好的方法吗?我没有找到任何关于重复模式的东西.
我不知道任何模式可以做你想要的,但你可以这样做:
let allSame L =
match L with
| [] | [_] -> L
| h::t when t |> List.forall ((=) h) -> L
| _ -> failwith "unpossible!" //handle the failing match here
Run Code Online (Sandbox Code Playgroud)
PS你在谈论一个序列,但你的匹配表明你正在使用一个列表.序列的相应代码就像是
let allSameSeq s =
match Seq.length s with
| 0 | 1 -> s
| _ when Seq.skip 1 s |> Seq.forall ((=) (Seq.head s)) -> s
| _ -> failwith "unpossible!"
Run Code Online (Sandbox Code Playgroud)
请注意,此功能的性能可能比基于列表的功能更差.
| 归档时间: |
|
| 查看次数: |
1466 次 |
| 最近记录: |