简体   繁体   English

OCaml虽然是真的循环

[英]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. 口译员抱怨第4行,这已经done ,我不知道这里有什么问题。
I understand that OCaml is a functional language and the variables are immutable. 我知道OCaml是一种函数式语言,变量是不可变的。 I should not try to change the value of a here. 我不应该尝试改变的价值a在这里。 But still, there is a while true do .. done loop in OCaml. 但是,仍然有一段while true do .. done在OCaml中while true do .. done循环。 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 ? 如何才能修改代码才能完成这项工作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. let ... in构造期望另一个表达式。 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. 但它会无限循环,因为在开始时定义为1的a与声明为+ 1的a不同。 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: 您可以通过使用ref函数及其处理程序指定as mutable来获得所需内容:

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. 请注意,通过使用while循环和可变值,您将失去FP的所有好处。

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. 如果你想做FP,不惜一切代价避免使用while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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