ocamllazylist

Ocaml use match with lazylist


I am trying to fill ma lazylist by unpaired elements (with recursion), starting with element k. For example: k = 2, list is [2,3,5,7,9,...] The code:

let lgen =
  let rec gen k = LCons(k, fun () -> gen k (k + 2))
  in gen 1;;

But how can I check is the element k unpaired? (I think that here I need to use match).


Solution

  • Assuming your type for lazy lists is something like this:

    type 'a llist = LNil | LCons of 'a * (unit -> 'a llist);;
    

    You can pattern match like this:

    let rec lfind e lxs =
        match lxs with
        | LNil -> false
        | LCons(x, _) when x > e -> false
        | LCons(x, xs) -> if e=x then true else lfind e (xs ())
        ;;