54 people like it.

Remove first ocurrence from list

Removes from list the first ocurrence only of an element that satisfies the predicate. Additional elements that also satisfy the predicate remain in the list.

Remove first ocurrence from list

1: 
2: 
3: 
4: 
5: 
let rec remove_first pred lst =
    match lst with
    | h::t when pred h -> t
    | h::t -> h::remove_first pred t
    | _ -> []

Usage:

1: 
2: 
3: 
4: 
5: 
let somelist = [('a',2);('f',7);('a',4);('h',10)]

let removed = somelist |> remove_first (fun (x,y) -> x='a')
// Result is:
// [('f',7);('a',4);('h',10)]
val remove_first : pred:('a -> bool) -> lst:'a list -> 'a list

Full name: Script.remove_first
val pred : ('a -> bool)
val lst : 'a list
val h : 'a
val t : 'a list
val somelist : (char * int) list

Full name: Script.somelist
val removed : (char * int) list

Full name: Script.removed
val x : char
val y : int

More information

Link:http://fssnip.net/1T
Posted:13 years ago
Author:Alexander Rautenberg
Tags: list