2012-04-25 57 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])