在ocaml中,有时我们在“let”后面需要两个分号,但有时我们不需要它们

问题描述 投票:0回答:1

下面两个let定义换行连接,这样就可以了

# let x = 1 + 2 * 3
  let y = (1 + 2) * 3;;
val x : int = 7
val y : int = 9

但是以下失败了。

let x = 3 
    

print_string "hello" ;;

错误:

let x = 3 
    
    print_string "hello" ;;
Error: This expression has type int
This is not a function; it cannot be applied.

上面可以通过放两个分号来固定。但是为什么有时候“let”后面需要两个分号,有时候不需要呢?

ocaml
1个回答
0
投票

OCaml 对空格不敏感。特别是,换行符永远不会影响代码的阅读(对于编译器)。因此,让我们在没有换行符的情况下重写您的两个示例。 第一个读作

let x = 3 let y = 1

这很好:我们有两个相互跟随的定义,定义开头的

let
允许我们将两个定义分开。

然而,第二个例子读作

let x = 3 print_string "hello"

在这里,我们将整数

3
应用于
print_string
函数,这是一个错误。 因此,如果我们想在像
let x = 3
这样的定义之后有一个顶层表达式,我们需要用
;;
将两者分开。

let x = 3 ;; print_string "hello"

或者我们可以将顶层表达式转换为不定义任何新变量的定义

let x = 3 let () = print_string "hello"
© www.soinside.com 2019 - 2024. All rights reserved.