How to generate recursive list in OCaml

前端 未结 5 885
抹茶落季
抹茶落季 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:48

    As far as I can see, OCaml doesn't lend itself to this kind of coding unless you want to descend into the unsafe parts of the language.

    Sticking to the safe parts of the language (but using extensions from Chapter 7), here is a (not very impressive) version of cycle that works for lists up to length 3:

    let cycle = function
        | [] -> []
        | [x] -> let rec res = x :: res in res
        | [x; y] -> let rec res = x :: q and q = y :: res in res
        | [x; y; z] -> let rec res = x :: t and t = y :: v and v = z :: res in res
        | _ -> failwith "list too long"
    

    It's easy to see how to extend this to any desired fixed length, but not to arbitrary length.

    Here's a session with the function:

    # #use "cyc.ml";;
    val cycle : 'a list -> 'a list = 
    # cycle [1;2;3];;
    - : int list =
    [1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1;
     2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2;
     3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3;
     1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1;
     2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2;
     3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; ...]
    

    This is the best I can do, at any rate. I hope it's helpful.

提交回复
热议问题