user3052477
user3052477

Reputation: 59

OCaml - Traversing a list without recursion

I'm trying to write following code without recursion:

let rec traverse lst =
  match lst with
  | a::b::t ->
      (* Something that return None*)
      traverse (b::t)
  | _ -> ()

How to do it in imperative way ?

Upvotes: 0

Views: 881

Answers (1)

gasche
gasche

Reputation: 31459

In an imperative way:

let traverse li =
  let state = ref li in
  while !state <> [] do
    let x = List.hd !state in
    state := List.tl !state;
    (* do whatever you want *)
  done

If you need to access the second element of the list, just use the appropriate List.hd call. But you may need to check that the list isn't empty first.

I see no reason to do that this way, which is heavier, less efficient and less flexible than a recursive loop.

Upvotes: 1

Related Questions