trakmack
trakmack

Reputation: 93

Trouble breaking out of a loop

I'm starting to learn OCaml, and I don't understand why this loops indefinitely:

let x = true in
while x do
    print_string "test";
    x = false;
done;;

What am I missing?

Upvotes: 0

Views: 108

Answers (3)

Thomas Leonard
Thomas Leonard

Reputation: 7196

It's best to run ocaml with warnings and strict sequence on to detect problems. e.g.

$ ocaml -strict-sequence -w A
    OCaml version 4.01.0

# let x = true in
  while x do
    print_string "test";
    x = false;
  done;;      
Error: This expression has type bool but an expression was expected of type
     unit

This shows the problem: x = false is testing whether x is false or not, not doing an assignment.

Upvotes: 1

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66813

One reason to study OCaml is to learn how to compute with immutable values. Here's a version that doesn't depend on a mutable variable:

let rec loop x =
    if x then
        begin
        print_string "test";
        loop false
        end
in
loop true

The trick is to reimagine the mutable values as function parameters, which allows them to have different values different times.

Upvotes: 4

that other guy
that other guy

Reputation: 123540

It's because OCaml let bindings are immutable. This exact issue is discussed in detail in the ocaml.org tutorial. Use a ref instead, and set and get the value it holds using ! and :=:

let x = ref true in 
    while !x do
        print_string "test";
        x := false
    done;;

Upvotes: 2

Related Questions