Ocaml运算符在匿名函数中

时间:2017-02-11 15:48:17

标签: ocaml

我正在尝试编写一个函数来解析列表并创建一个新列表,其中包含我在这种情况下名称所需的单词。

我可以为一个名字编写函数,例如

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

您正尝试在此处对两个字符串应用布尔||运算符,但这不起作用并导致类型错误。您需要分别使用x测试两个字符串的相等性,然后对结果执行OR:

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