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)]

Remove nth ocurrence from list

1: 
2: 
3: 
4: 
5: 
6: 
7: 
// This requires a small modification:
let rec remove_nth pred n lst =
    match lst, n with
    | (h::t, 1) when pred h -> t
    | (h::t, _) when pred h -> h::remove_nth pred (n-1) t
    | (h::t, _) -> h::remove_nth pred n t
    | _ -> []
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
val remove_nth : pred:('a -> bool) -> n:int -> lst:'a list -> 'a list

Full name: Script.remove_nth
val n : int

More information

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