2017-02-11 56 views
0

我想寫一個函數,將解析一個列表並創建一個新的列表,其中包含我想在這種情況下的名稱的話。Ocaml運營商在匿名函數

我可以令狀的功能一個名字e.g

let extract_name (lst : string list) : string list = 
List.filter (fun x -> x = "George") (lst) 

當我試圖寫它不止一個名字,我得到的錯誤。我重新安排了幾次括號,但仍然出現錯誤。

let extract_name (lst : string list) : string list = 
List.filter (fun x -> x = ("George" || "Victoria")) (lst) 

錯誤

let extract_name (lst : string list) : string list = 
List.filter (fun x -> x = "George" || "Victoria") (lst) 
;; 
Characters 93-103: 
List.filter (fun x -> x = "George" || "Victoria") (lst) 
             ^^^^^^^^^^ 
Error: This expression has type string but an expression was expecte of type bool 
# let extract_name (lst : string list) : string list = 
List.filter (fun x -> x = ("George" || "Victoria")) (lst);; 
Characters 82-90: 
List.filter (fun x -> x = ("George" || "Victoria")) (lst);; 
          ^^^^^^^^ 
Error: This expression has type string but an expression was expected  of type bool 

如何解決這個問題?

回答

3

您試圖在兩個字符串上應用布爾||運算符,這不起作用並導致類型錯誤。您需要單獨測試與x平等的兩個字符串,然後或者結果:

List.filter (fun x -> (x = "George") || (x = "Victoria")) lst 
+0

什麼,如果你想它在列表比較值是多少? – Tank

+0

然後用['fun x - > List.mem x [「George」,「Victoria」]'](https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html #VALmem) – Bergi