Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 531

OCaml for-loop seems to be re-executing more than expected

$
0
0

I have the following function

let update s =   for i=0 to ((Array.length s) - 2) do     for j=0 to (Array.length (s.(i))) - 2 do       (s.(i)).(j) <- (s.(i).(j)) + 1;    done;  done

and it seems to increase the relevant coordinates of the 2D array s by 2, for every one time that it is called.

Below is the full code in case it is helpful to see how I'm using these things.

backend.ml

type sim = int array arraylet create m n = Array.make m (Array.make n 0)let update s =   for i=0 to ((Array.length s) - 2) do     for j=0 to (Array.length (s.(i))) - 2 do       (s.(i)).(j) <- (s.(i).(j)) + 2;    done;  donelet toString s =  let rows = Array.length s in   if rows = 0 then "--\n||\n--"  else    let cols = Array.length s.(0) in     let st = ref "--\n" in    for i=0 to rows-1 do       for j=0 to cols-1 do         st := !st ^ (string_of_int s.(i).(j)) ^ ","      done;      st := !st ^ "\n"    done;    !st 

main.ml

open Test.Backendlet sim = create           (int_of_string Sys.argv.(1))           (int_of_string Sys.argv.(2));;while true do  print_endline (toString sim);  update sim;  Unix.sleepf 1.;done

The print-out from running this with command-line arguments 3 and 10 looks like the following.

--                                 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,--2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,0,--4,4,4,4,4,4,4,4,4,0,4,4,4,4,4,4,4,4,4,0,4,4,4,4,4,4,4,4,4,0,

I cannot even guess at why it's doing this. I threw around a bunch of parentheses, tweaked a few numbers, just to see if it would change anything. I also don't understand why this ever updates the final row since I tried subtracting "too much". I'm guessing this is somehow related to the problem of adding too many times. But as I try to logically parse it out, I just cannot see how this is happening.


After tinkering, I threw in a print line in the update function and found that the update function is getting called twice for every one time that the while-loop executes. So now I don't understand why that is happening, but it's progress!


Viewing all articles
Browse latest Browse all 531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>