2014-03-29 22 views
1

我在ocaml的新的和我寫了一些代碼來獲取列表這個模式匹配並不詳盡OCaml中

let rec n_elem l n = match n with 
| 0 -> match l with 
    | h::_ -> h 
    | _ -> failwith "erorr with empty list" 
| _ -> match l with 
    | h::t -> n_elem t (n-1) 
    | _ -> failwith "erorr with empty list" 
;; 

當我使用ocaml解釋它運行,一個警告作爲生成的n個元素:

Warning 8: this pattern-matching is not exhaustive. 
Here is an example of a value that is not matched: 
1 
Warning 11: this match case is unused. 

,當我運行它:

Printf.printf "%s\n" (n_elem ["a";"b";"c";"d"] 1);; 

它產生match_failure ...

任何人都可以給我一些幫助嗎?

回答

2

這基本上是一個優先問題。第二個_匹配的情況是第二個match表達式的一部分。您可以使用開始/結束將它們分開:

let rec n_elem l n = match n with 
| 0 -> 
    begin 
    match l with 
    | h::_ -> h 
    | _ -> failwith "erorr with empty list" 
    end 
| _ -> 
    begin 
    match l with 
    | h::t -> n_elem t (n-1) 
    | _ -> failwith "erorr with empty list" 
    end 
+0

aHa,完成!謝謝你Jeffrey :) – computereasy