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

OCaml

About me

ドイツの現地企業でWeb Developer/System Administratorとして働いているアラフォーおじさんです。

プログラミングとかコンピュータに関する事がメインですが、日常的なメモとか雑多なことも書きます。

Links :
目次