2015-12-01 73 views
1

我有這樣的名單:從列表中刪除項目時,我發現一個價值

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)];; 
+0

使用'List.filter'? – Marth

+0

請舉例 – daniele3004

回答

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. *) 

的跟隨着G功能將比較三的第一件具有恆定數量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)]  
+0

非常感謝 – daniele3004