Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression To Test That All Items In Sequence Are The Same

Is there a multiple instances pattern in F# somewhere?

Consider that I'm working on a list. I have the following pattern matching

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?

In other words passing [] or [1] should simply return the list and so should [1;1;1;...] but I can't figure out how to pattern match that last pattern. Is this possible? Or is there a better approach that I might use? I haven't found anything anywhere about a repeating pattern.

like image 554
Onorio Catenacci Avatar asked Dec 10 '22 18:12

Onorio Catenacci


1 Answers

I don't know of any pattern that does what you want, but you could do this:

let allSame L =
    match L with
    | [] | [_] -> L
    | h::t when t |> List.forall ((=) h) -> L
    | _ -> failwith "unpossible!" //handle the failing match here

P.S. You're talking about a sequence, but your match indicates that you're working with a list. The corresponding code for a sequence would be something like

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

Be warned that the performance of this function may well be worse than the list-based one.

like image 137
cfern Avatar answered May 23 '23 21:05

cfern