找到值时从列表中删除项目

时间:2015-12-01 13:19:42

标签: ocaml

我有这个清单:

let myList = [(1,2,0);(1,3,0);(1,4,0);(2,6,0);(3,5,0);(4,6,0);(6,5,0);(6,7,0);(5,4,0)];;

当第一个位置与数字相等时,我想删除列表中的每个元素,例如,如果我删除元素以1开头,则结果必须为:

[(2,6,0);(3,5,0);(4,6,0);(6,5,0);(6,7,0);(5,4,0)];;

1 个答案:

答案 0 :(得分:3)

来自OCaml' standard library

val filter : ('a -> bool) -> 'a list -> 'a list
(** filter p l returns all the elements of the list l that satisfy 
    the predicate p. The order of the elements in the input list is
    preserved. *)

以下函数将比较三元组的第一个元素与常数n

let first_is n (m,_,_) = n = m

然后您可以使用它来过滤您的列表:

List.filter (first_is 1) [1,2,3;4,5,6;7,8,9]

这将删除所有不满足谓词的元素,即,在给定示例中,它将返回仅包含一个三元组的列表:[1,2,3]

由于你想要相反,你可以定义谓词:

let first_isn't n (m,_,_) = n <> m

交互式顶层中的完整示例:

# let xs = [1,2,0;1,3,0;1,4,0;2,6,0;3,5,0;4,6,0;6,5,0;6,7,0;5,4,0];;
val xs : (int * int * int) list =
  [(1, 2, 0); (1, 3, 0); (1, 4, 0); (2, 6, 0); (3, 5, 0); (4, 6, 0);
   (6, 5, 0); (6, 7, 0); (5, 4, 0)]
# let first_isn't n (m,_,_) = n <> m;;
val first_isn't : 'a -> 'a * 'b * 'c -> bool = <fun>
# List.filter (first_isn't 1) xs;;
- : (int * int * int) list =
[(2, 6, 0); (3, 5, 0); (4, 6, 0); (6, 5, 0); (6, 7, 0); (5, 4, 0)]