OCamlで無限リスト
こんな感じのコードになりました。正しいかどうか自信はありません。。。
utop # type endless_list = Nil | Cons of int * (unit -> endless_list);;
utop # let get = function | Nil -> failwith "get" | Cons(head, _) -> head;;
utop # let next = function | Nil -> failwith "next" | Cons(_, f) -> f();;
utop # let rec list_sequential n = Cons (n, fun () -> list_sequential (n+1));;
utop # let loop from term f =
let rec loop' list i =
match i with
| v when v = term -> Nil
| _ -> begin
f (get list);
loop' (next list) (i+1)
end
in
loop' (list_sequential from) 0
;;
実行結果は以下のような感じになります。
utop # loop 0 10 (fun n -> print_endline (string_of_int n));;
0
1
2
3
4
5
6
7
8
9
- : delay_list = Nil
loop
関数はmap
出来るような形式にしたほうが良いのかな?と一瞬思いましたが、そうするとそれはおそらく無限リストを使うようなものでは無いので見送りました。
ただ、fold_left
的な動作が出来るように実行結果は内部再帰関数loop'
で受け取れるようにした方が良いような気もします。
公開日:2020/07/23