Search code examples
filterf#fold

F# filter out only first occurrence from list


I have a list and I want to remove an element matching some criteria but remove only one element.

let items = [1;2;3]

let predicate x =
    x >= 2

let result = items |> List.fold ...
// result = [1;3]

How to achieve method returning list with [1;3]?


Solution

  • You can use a generic recursive function

    let rec removeFirst predicate = function
        | [] -> []
        | h :: t when predicate h -> t
        | h :: t -> h :: removeFirst predicate t
    

    or a tail recursive one (if you fear a stack overflow)

    let removeFirst predicate list =
        let rec loop acc = function
            | [] -> List.rev acc
            | h :: t when predicate h -> (List.rev acc) @ t
            | h :: t -> loop (h :: acc) t
        loop [] list