The following function removes the first occurrence of an item in a list:

let rec removeFirstOccurrence item screened items =

    items |> function
    | h::tail -> if h = item
                 then screened @ tail
                 else tail |> removeFirstOccurrence item (screened @ [h])
    | _ -> []

I needed the code to remove items from a shopping cart that I built:

Untitled.png

Here’s how I referenced it:

let remove : Remove =

    fun product cart -> 

        let products = cart.Products |> nonEmptyToList
        let updated  = products |> removeFirstOccurrence product []

        if List.isEmpty updated
        then Empty    { Shopper = cart.Shopper }
        else NonEmpty { Shopper = cart.Shopper; CartId= cart.CartId; Products= { Head= updated.Head; Tail=updated.Tail } }
Advertisements