Search code examples
for-loopgraphocaml

For loops in ocaml


I want to do something like the following.

let switchgraph cases =
  let g = Graph.makeGraph() in
  let g = (Graph.addNode g 1) in
  for i = 2 to cases do 
    let g = (Graph.addNode g i) in
  done
  g

But apparently, this is not possible. How else can I achieve this?


Solution

  • There are two things you need to fix:

    • you need to use references (see ref, := and !) for this, since let bindings are immutable
    • to sequence two expressions, you need to use ;

    Something like this should work:

    let switchgraph cases =
        let g = ref (Graph.makeGraph()) in
        g := Graph.addNode (!g) 1;
        for i = 2 to cases do
            g := Graph.addNode (!g) i
        done;
        !g
    

    Note that g is the reference, and !g the value.