Loading ...
Sorry, an error occurred while loading the content.

Re: "ocaml_beginners"::[] Counter in List.iter?

Expand Messages
  • Florent Monnier
    ... In recent version of OCaml there s List.iteri, otherwise you can use List.fold_left instead: let _ = List.fold_left (fun i w - print_endline
    Message 1 of 9 , Nov 22, 2012
    • 0 Attachment
      2012/11/20, George <siberianowl@...>:
      > I have a list with words. I need to print them and number them.
      > The only way I found to do it is by using reference variables:
      >
      > let i = ref 1 in
      > List.iter (fun w ->
      > print_endline (string_of_int !i) ^ ": " ^ w;
      > i := !i+1
      > ) words;;
      >
      > Is there a better way?

      In recent version of OCaml there's List.iteri, otherwise you can use
      List.fold_left instead:

      let _ =
      List.fold_left (fun i w ->
      print_endline ((string_of_int i) ^ ": " ^ w);
      (i+1)
      ) 1 words;;

      --
      Cheers
    Your message has been successfully submitted and would be delivered to recipients shortly.