あなただけのリストの最初と最後の要素にチェックを作っている場合は、代わりに、パターンマッチングの条件文を使用することもできます。
let is_valid l =
let open List in
let hd' = hd l in (* Get the first element of the list *)
let tl' = rev l |> hd in (* Get the last element of the list *)
if hd' = 1 && tl' = 9 then true else false
is_valid [1;2;3;4;5;6;9] (* bool = true *)
をしかし、あなたはその真ん中を抽出しようとしている場合パターンマッチングを使用する価値があるかもしれません。あなたは、単純なパターンマッチングでそれを使用することができ、この機能を次に
let is_valid l =
let open List in
match l with
| 1 :: mid -> (* `mid` holds list without the `1` *)
(match rev mid with (* `rev_mid` holds list without the 9 but reversed *)
| 9 :: rev_mid -> Some (rev rev_mid) (* reverse to get correct order *)
| _ -> None)
| _ -> None
is_valid [1;2;3;4;5;6;9] (* int list option = Some [2; 3; 4; 5; 6] *)
:私たちは、理由は彼が指摘した理由(パターンマッチングは、リストの末尾にマッチすることはできません)のジェフリーが提案するものに似た何かを行うことができます有効なリストの真ん中を探す: