当我找到一个值时从列表中删除项目
Removing items from a list when I find a value
我有这个列表:
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)];;
来自 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]
这将删除所有不满足谓词的元素,即在给定的示例中,它将 return 一个只有一个三元组的列表:[1,2,3]
.
既然要相反,那么可以定义predicate:
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)]
我有这个列表:
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)];;
来自 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]
这将删除所有不满足谓词的元素,即在给定的示例中,它将 return 一个只有一个三元组的列表:[1,2,3]
.
既然要相反,那么可以定义predicate:
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)]