首页 > 解决方案 > OCaml 计数器在不使用线程的情况下不会终止

问题描述

我有以下代码:

let counter n = 
    let rec count i = 
    if i > n 
      then ()
      else 
          print_int i; 
          count (i+1)
    in count 0

它应该简单地输出从 0 到 n 的所有数字。澄清一下,我知道有更简单的方法可以达到相同的结果,但我想知道为什么它在这种特定情况下不起作用。当我使用某些参数运行此代码时,例如。counter 5它不会终止。

相反,当我将代码的最后一行更改为in count 0输出in Thread.create count 0012345

有人可以解释这种行为吗?

编辑

还发现如果把代码修改成这样:

let counter n = 
    let rec count i = 
    if i > n 
      then ()
      else 
          let i = i
          in print_int i; 
          count (i+1)
    in count 0

它工作正常。为什么是这样?

标签: multithreadingfunctional-programmingocamlcounter

解决方案


您的缩进具有误导性;你的代码确实

if i > n then () else print_int i; 

先后

count (i+1)

当然不会终止!你想要的是

else begin
  print_int i; 
  count (i+1)
end

(或else ( ... ))。请参阅https://ocaml.org/learn/tutorials/if_statements_loops_and_recursion.html中的“使用 begin ... end” 。


推荐阅读