How to generate recursive list in OCaml

前端 未结 5 890
抹茶落季
抹茶落季 2021-01-21 06:05

I would like to implement analog of Haskell cycle function.

If I pass list elements explicitly it seems trivial:

let cycle a b c =
  let rec         


        
5条回答
  •  臣服心动
    2021-01-21 06:53

    You can define it like so also

    # let cycle items =
        let buf = ref [] in
        let rec next i =
          if !buf = [] then buf := items;
          match !buf with
            | h :: t -> (buf := t; Some h)
            | [] -> None in
        Stream.from next;;
    val cycle : 'a list -> 'a Stream.t = 
    
    utop # let test = cycle [1; 2; 3];;
    val test : int Stream.t =  
    utop # Stream.npeek 10 test;;
    - : int list = [1; 2; 3; 1; 2; 3; 1; 2; 3; 1]
    

    This is from:

    http://ocaml.org/tutorials/streams.html

提交回复
热议问题