Counting the number of elements that don't change in a list, in F#

Viewed 80

I have a simple list:

let l = [ 1; 1; 1; 1; 2; 1; 1; 1 ]

I want to know how many elements match the first one, without a break (4 in the example)

let mutable i = 0
while l.[i] = l.[0] do
    i <- i + 1

But is there a more F# idiomatic way to do this? through one of the list functions?

2 Answers
let l = [ 1; 1; 1; 1; 2; 1; 1; 1 ]
let res = 
    l
    |> Seq.takeWhile(fun i -> i = l.Head)
    |> Seq.length

Here's a way to "do it yourself" in the functional paradigm, using a tail-recursive helper function:

let countInitialRun lst =
    // count how many times value appears at the start of lst
    let rec helper value lst counter =
        match lst with
        | head :: tail when head = value -> helper value tail (counter + 1)
        | _ -> counter
    // call the helper function
    // initial counter is 1 because the head is already counted
    match lst with
    | [] -> 0
    | head :: tail -> helper head tail 1
Related