無限数列
整数の無限数列のジェネレータみたいなもの。
# type intseq= Cons of int * (int -> intseq);; type intseq = Cons of int * (int -> intseq)
フィボナッチ数列のジェネレータ
# let fib = let rec f x y = Cons (x, f (x+y)) in Cons (1, f 1);;
実際に計算する関数
# let rec nthseq n (Cons (x, f)) = if n = 1 then x else nthseq (n-1) (f x);; val nthseq : int -> intseq -> int = <fun>
結果
# nthseq 1 fib;; - : int = 1 # nthseq 2 fib;; - : int = 1 # nthseq 3 fib;; - : int = 2 # nthseq 4 fib;; - : int = 3 # nthseq 5 fib;; - : int = 5 # nthseq 6 fib;; - : int = 8 # nthseq 7 fib;; - : int = 13 # nthseq 8 fib;; - : int = 21 # nthseq 9 fib;; - : int = 34 # nthseq 10 fib;; - : int = 55
リスト形式で結果を得るようにしてみた。
# let rec repeat n f x = if n = 0 then [] else f x :: repeat (n-1) f (f x);; val repeat : int -> ('a -> 'a) -> 'a -> 'a list = <fun> # let rec map f = function [] -> [] | x :: rest -> f x :: map f rest;; # map (fun (Cons (x, f)) -> x) (repeat 10 (fun (Cons (x, f)) -> f x) fib);; - : int list = [1; 1; 2; 3; 5; 8; 13; 21; 34; 55]