c-cube/ocaml-containers

CCList.unfold

benbellick opened this issue ยท 0 comments

Hi Simon! ๐Ÿ˜„

Wondering if there is a reason why CCList doesn't have an unfold function like e.g.:

let rec unfold f seed =
  match f seed with
    | None -> []
    | Some (v, next) -> v :: unfold f next

This has type:
('a -> ('b * 'a) option) -> 'a -> 'b list

One obvious problem may be that this is unsafe in the sense that the following would result in a stack overflow:

let f = fun _ -> Some (true, true);;
unfold f 0;;
(*Stack overflow during evaluation (looping recursion?).*)

Given that, how about having a safe version of unfold which also takes a max parameter which stops the computation if the max is reached? Or maybe having an unsafe unfold is fine. Anyways, if there is interest in adding this in and no qualms, I'll write up a PR this weekend! Thanks