I donβt think there is any function that would allow you to directly present the idea that you want to remove only the first element that matches the specified criteria from the list (for example, something like Seq.removeOne ).
You can implement the function in a relatively easy to read way using Seq.fold (if the sequence of numbers is finite):
let removeOne fl = Seq.fold (fun (removed, res) v -> if removed then true, v::res elif fv then true, res else false, v::res) (false, []) l |> snd |> List.rev > removeOne (fun x -> x = 6) [ 1; 2; 6; 6; 1 ]; val it : int list = [1; 2; 6; 1]
The fold function saves some state β in this case, the type bool * list<'a> . The Boolean flag means that we have already deleted an element, and the list is used to accumulate the result (which should be canceled at the end of processing).
If you need to do this for an (possibly) infinite seq<int> , you will need to use GetEnumerator directly and implement the code as an expression of a recursive sequence. This is a little uglier and it will look like this:
let removeOne f (s:seq<_>) = // Get enumerator of the input sequence let en = s.GetEnumerator() let rec loop() = seq { // Move to the next element if en.MoveNext() then // Is this the element to skip? if f en.Current then // Yes - return all remaining elements without filtering while en.MoveNext() do yield en.Current else // No - return this element and continue looping yield en.Current yield! loop() } loop()
source share