multithreading - 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 0
时012345
有人可以解释这种行为吗?
编辑
还发现如果把代码修改成这样:
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
它工作正常。为什么是这样?
解决方案
您的缩进具有误导性;你的代码确实
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” 。
推荐阅读
- reactjs - 我的反应应用程序没有像代码一样在 github 页面中看到
- sql - Hive 中的查询语法
- bash - 清理基于文件的变量。错误:作业失败:退出代码 1
- python - 从两个图像中找到裁剪参数
- python-3.x - Pandas 日期从“2020 年 10 月 23 日;2020 年 8 月 27 日”转换为“2020 年 10 月 23 日;2020 年 8 月 27 日”
- kotlin - kotlinx-serialization - 为什么从基类继承的默认值总是被编码?
- c - strtok 的大小 1 无效
- android - 如何使用 Flutter 加快 Webview 中的自动登录?
- java - 致命信号 11 (SIGSEGV),代码 1,tid 1597 中的故障地址 0x0(电话服务器)
- ios - “任何”类型的值没有成员“标题”