gpt4 book ai didi

return-value - OCaml 返回值

转载 作者:行者123 更新时间:2023-12-04 04:16:31 26 4
gpt4 key购买 nike

在'Developing Applications with OCaml'一书中,关于返回值有以下解释:

As the value preceding a semicolon is discarded, Objective CAML gives a warning when it is not of type unit.

# print_int 1; 2 ; 3 ;;
Characters 14-15:
Warning: this expression should have type unit.
1- : int = 3


To avoid this message, you can use the
function ignore:

# print_int 1; ignore 2; 3 ;;
1- : int = 3`


我不明白为什么 2 会有问题返回值不同于 unit ,因为我的意图不是返回 2 , 但要返回 3 .按照我的理解,我最后一条指令之前的任何指令都不是函数的返回值,那么为什么会出现警告呢?

我的代码中一直有这个警告,我越来越清楚我并不真正理解返回值在 OCaml 中是如何真正工作的。

谢谢你的帮助。

最佳答案

考虑表达式 e1 ; e2 .根据定义 - 评估整个表达式会导致评估 e1然后 e2整个表达式的结果值是 e2 的值. e1 的值结果被丢弃。如果 e1 的类型,这不是问题是 unit因为它只有一个居民值 () .对于所有其他类型丢弃 e1 的结果意味着丢失可能不是程序员想要的信息,因此是警告。程序员必须明确地忽略结果值,或者使用 ignore或与

let (_:type) = e1 in
e2

可以省略类型注释,但确保 e1 可能很有用完全评估为预期类型(不是部分应用程序)。

关于return-value - OCaml 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6353988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com