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

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

Expand Messages
  • Francois Berenger
    ... For your info, this line: i := !i+1 is incr i in the standard library (increment an integer reference). ... List.iteri (fun i w - Printf.printf %d: %s n
    Message 1 of 9 , Nov 21, 2012
    • 0 Attachment
      On 11/20/2012 10:20 PM, George wrote:
      > 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

      For your info, this line:
      i := !i+1
      is
      incr i
      in the standard library (increment an integer reference).

      But otherwise, the code you are looking for is:

      ---
      List.iteri
      (fun i w -> Printf.printf "%d: %s\n" i w)
      words
      ---

      Or, a little shorter if you use the List and Printf modules a lot:

      ---
      module L = List
      module P = Printf

      L.iteri
      (fun i w -> P.printf "%d: %s\n" i w)
      words
      ---

      > ) words;;
      >
      > Is there a better way?
      >
      >
    • 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 2 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.