List.rev和空列表[]

Quy*_*yen 1 ocaml list pattern-matching

我真的不了解函数(parse_list)

None -> List.rev isNone -> []

let try_parse parse x = try Some (parse x) with Error _ -> None;;

let parse_list parse =
  let rec aux is = function
    | [] -> List.rev is, []
    | (hd :: tl) as xs ->
    match try_parse parse hd with
      | Some i -> aux (i::is) tl
      | None -> List.rev is, xs
  in aux [];;
Run Code Online (Sandbox Code Playgroud)

let parse_list parse =
  let rec aux is = function
    | [] -> List.rev is, []
    | (hd :: tl) as xs ->
    match try_parse parse hd with
      | Some i -> aux (i::is) tl
      | None -> [], xs
  in aux [];;
Run Code Online (Sandbox Code Playgroud)

他们不一样吗?如果他们不同,你能给我一个例子吗?非常感谢你

cag*_*ago 6

是的,他们是不同的.

在第一个中,当解析函数失败时,该函数parse_list将返回"已解析"表达式(List.rev is)的部分列表.

在第二个中,当解析函数失败时,您将从parse_list ([])获得一个空列表.

使用解析函数查看此示例,该函数仅保留小于的整数3:

let test_parse x = if x < 3 then x else raise Error "error";;
Run Code Online (Sandbox Code Playgroud)

通过第一个实现,您将获得:

# parse_list test_parse [1; 2; 3; 4; 5];;
  - : int list * int list = ([1; 2], [3; 4; 5])
Run Code Online (Sandbox Code Playgroud)

第二个,你会得到:

# parse_list test_parse [1; 2; 3; 4; 5];;
  - : int list * int list = ([], [3; 4; 5])
Run Code Online (Sandbox Code Playgroud)