OCaml语法陷阱:使用分隔符的多个让 [英] OCaml syntax trap: multiple lets using separators

查看:98
本文介绍了OCaml语法陷阱:使用分隔符的多个让的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自学OCaml.我在这个语法陷阱上一直疯了.有人告诉我,您可以使用;"按顺序将表达式字符串连接在一起即expr1; expr2按预期执行第一个expr,然后执行第二个.出于某种原因,我无法让口译员同意以下输入内容

I am trying to teach myself OCaml. I've been going nuts over this one syntax trap. I'm told that you can string expressions together in sequence using ";" ie, expr1 ; expr2 executes the first expr, then the second, as expected. For some reason, I cannot get the interpreter to agree with the following input

let x = 5 ; let y = 7;;

很奇怪,如果只有第一个expr是let,它就可以工作.所以

Bizarrely if ONLY the first expr is a let, it works. So

let x = 5 ; 7;;

通过,评估为7. 更糟糕的是,如果我尝试使用parens组成让let首先出现的多个语句序列,它仍然无法正常工作.即:

Passes, and evaluates to 7. Even worse, if I attempt to use parens to compose multiple sequences of statements where the let comes first, it still does not work. I.E.:

let x = 5 ; (let y = 7 ; 9);;

是错误,即使它仅包含以let为第一个表达式的序列组成.有人可以解释如何使其正常工作吗?

Is an error, even though it consists only of sequences where lets are the first expression. Can someone explain how to get this to work?

推荐答案

一种查看问题的方法是let x = 5不是表达式.这是一个顶层声明;也就是说,它声明了名称x,其值为5.

One way to look at the problem is that let x = 5 isn't an expression. It's a top-level declaration; i.e., it declares a name x with a value 5.

;运算符用于组合表达式,但不适用于声明.

The ; operator works for combining expressions, but not for declarations.

您不需要将声明与;一起使用.您可以一个接一个地放置:

You don't need to string declarations together with ;. You can just put one after the other:

# let x = 5 let y = 7;;
val x : int = 5
val y : int = 7
# 

OCaml中let完全不同的用法是表达式的一部分.在这种情况下,其后是in:

There is a completely different use of let in OCaml that is part of an expression. In that case it's followed by in:

# (let x = 4 in x + 1);;
- : int = 5

由于这是一个表达式,因此您可以将其中几个与;一起串起来:

Since this is an expression, you can string several of them together with ;:

# (let x = 4 in x + 1); (let y = 6 in y + 1);;
Warning 10: this expression should have type unit.
- : int = 7

但是,正如编译器警告您的那样,将任意表达式串在一起并不是习惯性的做法.通常,您将;与命令性代码一起使用.使用功能代码没有任何意义.因此,编译器希望除最后一个表达式外的所有表达式都具有unit类型(用于命令性代码,该命令执行有用的操作,但不返回有用的值).

However, as the compiler is warning you, it's not idiomatic to string together arbitrary expressions. Normally you use ; with imperative code. With functional code it doesn't make sense. So the compiler expects all but the last expression to have type unit (which is used for imperative code that does something useful but doesn't return a useful value).

这篇关于OCaml语法陷阱:使用分隔符的多个让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆