Basic question on looping

How do i print the number 1 unto 100 without using some higher library function ?
How do i do it in a loop ?
[This questions refers offcourse to mutable state ]

for i = 1 to 100 do
  print_endline (string_of_int i)
done

Cheers,
Nicolas

3 Likes

Does i has as type “ref int” ?
Can you print the type of i in the loop ?

i is just an int there. One hint that it’s not a ref is that you would have to do !i or i.contents to get the value out of a ref int (in string_of_int i in nojb’s examle). If you specifically wanted to see what it would be like with a mutable int, it might be something like:

let i = ref 0 in
while !i <= 100 do
  print_endline (string_of_int !i);
  incr i
done

(incr is a function for incrementing a mutable int, it could also be written i := !i + 1)

But it makes more sense to do what nojb mentioned, unless there’s some other context that requires a mutable int for some reason.

2 Likes

It is perhaps worth mentioning that ocaml implements tail call elimination, so if you are not going to use a for loop it would be more idiomatic in a functional language like ocaml to use recursive iteration instead of mutable state:

let () =
  let rec loop i =
    print_endline (string_of_int i) ;
    if i <= 100 then loop (i + 1) in
  loop 1
2 Likes