let rec sumList xs =
match xs with
| [] -> 0
| y::ys -> y + sumList ys let rec sumListTailRecHelper accumulator xs =
match xs with
| [] -> accumulator
| y::ys -> sumListTailRecHelper (accumulator+y) ys
let sumListTailRec xs = sumListTailRecHelper 0 xstype Expr =| Num of int| Add of Expr * Exprlet rec eval exp = match exp with| Num n -> n| Add (x,y) -> eval x + eval yeval (Add(Num 1, (Add(Num 2, Num 3))))|> printfn "%A" // 6
let 関数名 list =// 関数内部に再帰関数//(必要に応じて追加のパラメータをもつ)let rec loop xs =// リストをパターンマッチングmatch xs with// リストが空のとき| [] -> ...// リストがあるとき (必要に応じて再帰する)| h :: t -> ...// 再帰関数の呼び出しloop list
(* ('T -> bool) -> 'T list -> bool *)
let exists predicate list =
let rec loop xs =
match xs with
| [] -> false
| h :: t -> if predicate h then true else loop t
loop list(* ('T -> 'U list) -> 'T list -> 'U list *)
let collect mapping list =
let rec loop xs acc =
match xs with
| [] -> acc
| h :: t ->
let x = mapping h
loop t (match x with
| [] -> acc | ys -> append acc ys)
loop list [](* ('T -> bool) -> 'T list -> 'T list *)
let filter predicate list =
let rec loop xs cont =
match xs with
| [] -> cont []
| h :: t ->
let x = predicate h
loop t (fun acc ->
cont (if x then (h :: acc) else acc))
loop list idこのコードを前頁の実装で分解してみると
filter (fun x -> x % 2 = 1) [1;2;3] // [1; 3]let cont = idlet cont = fun acc -> cont (if true then (1 :: acc) else acc)let cont = fun acc -> cont (if false then (2 :: acc) else acc)let cont = fun acc -> cont (if true then (3 :: acc) else acc)cont [] // [1; 3]