简体   繁体   中英

OCaml while true do loop

I have the following code:

let a = 1 in
while a<10 do
  let a = a+1 in
done
Printf.printf "the number is now %d\n" a

The interpreter is complaining about line 4, which is done and I have no idea what is wrong here.
I understand that OCaml is a functional language and the variables are immutable. I should not try to change the value of a here. But still, there is a while true do .. done loop in OCaml. I hope you get the idea of what I am trying to do here. How shall I modify the code to do this job with while true do .. done ?
I am very new to functional programming. Please teach me the right way to get started with it. I find myself stuck in the deadlock of thinking imperatively.

The let ... in construct expects another expression behind. You can, for example use the () value (which basically means "nothing")

So the code

let a = 1 in
while a<10 do
   let a = a+1 in
   ()
done
Printf.printf "the number is now %d\n" a

It will compile. But it will loop indefinitely because the a defined as 1 at start is different than the a declared as a+1. Both are constant different values on different scopes, and a declaration inside the body of a while is limited to that occurence of the body.

You may get what you want by specifying a as mutable using the ref function and its handlers:

let a = ref 1 in
while !a < 10 do
 a := !a + 1
done
Printf.printf "the number is now %d\n" !a

Note that you loose all the benefits of FP by using a while loop and mutable values.

To do it in a functionnal manner, you can use a recursive function:

let rec f a =
 if a < 10
 then f (a+1)
 else a
in
let a = f 1 in
Printf.printf "the number is now %d\n" a

This one is the true right manner to do the job. If you want to do FP, avoid at all costs to use a while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM