这个 OCaml 代码有什么问题?

发布于 2024-09-08 18:04:17 字数 625 浏览 1 评论 0原文

这段代码有什么问题?

let vm_run vm =
    let guard = ref true in
    while !guard do
        if vm.cur_pc = -1 && not (Stack.empty vm.call_stack) then vm_pop_ar vm
        else if vm.cur_pc = -1 then guard := false
        else if vm.cur_pc < Array.length vm.cur_code then
            execute vm Array.get vm.cur_code vm.cur_pc;
            vm.cur_pc <- vm.cur_pc + 1
        else vm_pop_ar vm
    done

错误是与最后一个 else 关键字相关的错误:语法错误

我对 OCaml 有了很好的信心,但是 if/else 链仍然给我带来了一些麻烦......这不是第一次(上次我利用 flow 来避免使用 else 关键字)。

我认为它很小但没有任何线索,根据语法规范应该没问题

What's wrong with this code?

let vm_run vm =
    let guard = ref true in
    while !guard do
        if vm.cur_pc = -1 && not (Stack.empty vm.call_stack) then vm_pop_ar vm
        else if vm.cur_pc = -1 then guard := false
        else if vm.cur_pc < Array.length vm.cur_code then
            execute vm Array.get vm.cur_code vm.cur_pc;
            vm.cur_pc <- vm.cur_pc + 1
        else vm_pop_ar vm
    done

Error is Error: Syntax error related to the last else keyword.

I reached good confidence with OCaml but an if/else chain still gives me some troubles.. that's not the first time (last time I exploited flow to avoid using the else keyword).

I think it's something small but have no clues, according to syntax specification it should be ok

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声静候 2024-09-15 18:04:17

分号的优先级低于 if-else,因此当您需要在 if 内使用由分号分隔的两个或多个语句块时,需要将它们括在括号或 begin 中...end 块(两者是等价的):

    else if vm.cur_pc < Array.length vm.cur_code then begin
        execute vm Array.get vm.cur_code vm.cur_pc;
        vm.cur_pc <- vm.cur_pc + 1
    end
    else vm_pop_ar vm

The semicolon has lower precedence than if-else, so when you need to have a block of two or more statements separated by semicolons inside an if, you need to enclose them in parentheses or a begin...end block (the two are equivalent):

    else if vm.cur_pc < Array.length vm.cur_code then begin
        execute vm Array.get vm.cur_code vm.cur_pc;
        vm.cur_pc <- vm.cur_pc + 1
    end
    else vm_pop_ar vm
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文