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?

换句话说,传递[]或[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

P.S。你在谈论一个序列,但你的匹配表明你正在使用一个列表。序列的相应代码类似于

let allSameSeq s = 
    match Seq.length s with
    | 0 | 1 -> s
    | _ when Seq.skip 1 s |> Seq.forall ((=) (Seq.head s)) -> s
    | _ -> failwith "unpossible!"

请注意,此功能的性能可能比基于列表的功能更差。

其他提示

这是一个使用多案例活动模式的解决方案。

let (|SingleOrEmpty|AllIdentical|Neither|) (lst:'a list) =
    if lst.Length < 2 then
        SingleOrEmpty
    elif List.forall (fun elem -> elem = lst.[0]) lst then
        AllIdentical
    else
        Neither

let allElementsIdentical lst:'a list =
    match lst with
    |SingleOrEmpty|AllIdentical -> lst
    |Neither -> failwith "Not a suitable list"

我考虑做以下其中一项:


yourSequence |> Seq.windowed(2) |> Seq.forall(fun arr -> arr.[0] = arr.[1])


let h = Seq.hd yourSequence
yourSequence |> Seq.forall((=) h)

尽可能使用库函数总是很好;)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top