OCaml 返回值
在《使用 OCaml 开发应用程序》一书中,关于返回值有以下解释:
由于分号前面的值被丢弃,当它不是单位类型时,Objective CAML 会发出警告。
<前><代码># print_int 1; 2 ; 3 ;; 字符 14-15: 警告:此表达式应具有单位类型。 1- : 整数 = 3 为了避免出现此消息,您可以使用 函数忽略: # print_int 1;忽略 2; 3 ;; 1- : 整数 = 3`
我不明白为什么 2
的返回值与 unit
不同会出现问题,因为我的意图不是返回 2
,但返回3
。按照我的理解,最后一条指令之前的任何指令都不是函数的返回值,那么为什么会出现警告呢?
我的代码中一直出现此警告,而且我越来越清楚,我并不真正了解返回值在 OCaml 中的实际工作原理。
感谢您的帮助。
In the book 'Developing Applications with OCaml', there is the following explanation regarding return values:
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`
I don't understand why it would be a problem that 2
has a return value diferent than unit
, because my intention is not to return 2
, but to return 3
. The way I understand it, any instruction preceding my very last instruction is not the return value of the function, so why the warning?
I've been having this warning all over my code and it is becoming clear to me that I don't really understand how return values really work in OCaml.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑表达式 e1 ; e2。根据定义 - 计算整个表达式会导致计算
e1
,然后计算e2
,整个表达式的结果值为e2
的值。e1
的值结果被丢弃。如果e1
的类型是unit
,这不是问题,因为它具有唯一的单个居民值()
。对于所有其他类型,丢弃 e1 的结果意味着丢失信息,这可能不是程序员想要的,因此会出现警告。程序员必须明确忽略结果值,可以使用
ignore
或使用 Type 注释来省略,但确保e1
完全评估为预期值可能很有用类型(不是部分应用程序)。Consider expression
e1 ; e2
. By definition - evaluating this whole expression results in evaluation ofe1
and thene2
and the resulting value of the whole expression is the value ofe2
. Value result ofe1
is discarded. This is not the problem if the type ofe1
isunit
cause it has the only single inhabitant value()
. For all the other types discarding the result ofe1
means loosing information which is probably not what the programmer intended, hence the warning. The programmer has to explicitely ignore the result value, either withignore
or withType annotation can be omitted but it may be useful to be sure that
e1
is fully evaluated to the expected type (not a partial application).嗯,警告之所以存在,是因为您生成一个值但随后不使用它这一事实可能(并且非常经常是)表明您做错了什么。如果您不同意此政策,您可以关闭该警告。但像往常一样,最好不要这样做,在这种情况下,如果您确实不需要表达式的值,您确实可以使用忽略或将其绑定到
_
,如让 _ = f() in ...
。Well, the warning is there because the fact that you produce a value but then don't use it may be (and very often is) an indication that you are doing something wrong. If you don't agree with this policy you can turn off that warning. But as usual it's a good practice not to do that, in which case, if you really don't need a value of an expression you can indeed use ignore or bind it to
_
, as inlet _ = f() in ...
.