2011-01-23 16 views
8

私は整数型のリスト[1; 2; 3; 4; 5; 6; 7; 8]と私は一度に最初の3つの要素を一致させるパターンにしたい。ネストされたマッチステートメントなしでこれを行う方法はありますか?リスト内の複数の要素を一度に一致させるOcamlパターン

たとえば、このようにすることはできますか?

let rec f (x: int list) : (int list) = 
begin match x with 
| [] -> [] 
| [a; b; c]::rest -> (blah blah blah rest of the code here) 
end 

私は次のようになり、長いネストされた方法で、使用できます。

let rec f (x: int list) : (int list) = 
begin match x with 
| [] -> [] 
| h1::t1 -> 
    begin match t1 with 
    | [] -> [] 
    | h2::t2 -> 
    begin match t2 with 
    | [] -> [] 
    | t3:: h3 -> 
     (rest of the code here) 
    end 
    end 
end 

感謝を!

答えて

11

はい、できます。構文は次のようなものです:

let rec f (x: int list) : (int list) = 
begin match x with 
| [] -> [] 
| a::b::c::rest -> (blah blah blah rest of the code here) 
end 

ができますが、リストには、三つの要素よりも少ないを持っている場合、これは失敗することがわかります。 1つまたは2つの要素リストのケースを追加することも、何かに一致するケースを追加することもできます。

let rec f (x: int list) : (int list) = 
    match x with 
    | a::b::c::rest -> (blah blah blah rest of the code here) 
    | _ -> [] 
+0

ありがとう!そして、ここでコードの残りの部分を言ってみましょう。私は要素 "a"を除くすべてを返すことを望みました。私はちょうどb @ c @ restをしますか? – chesspro

+2

'a ::((b :: c :: rest)as tl)'とマッチして、リストの先頭要素を作り直すことなく 'tl'を使うことができます。 – nlucaroni

+0

これは知りませんでした、ありがとう! – chesspro

関連する問題