2012-04-25 25 views
1

我不是真的在List.rev和空列表[]

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 [];; 

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 [];; 

它们是不同的理解有关的函数(parse_list)?如果他们不同,请给我一个例子吗?非常感谢

回答

6

是的,它们是不同的。

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

在第二个,解析函数将失败时,您将从parse_list[])得到一个空列表。

看这个例子具有解析功能,将只保留整数比3较小:

let test_parse x = if x < 3 then x else raise Error "error";; 

有了第一次执行,你会得到:

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

机智的第二个,你”将得到:

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