2013-05-28 31 views
1
let x = 132;; 
let f x = 
    let x = 15 in (fun x -> print_int x) 150;; 
f 2;; 

输出为150OCaml的语法环境和语法错误

我的问题是:为什么“print_int”不执行了吗?是因为fun x-> print_int x只是定义了一个函数,但不需要执行呢?里面的功能只是打印15吗?

我想给我的猜测作出回应,当我修改代码以这样的:提示

# let x = 132;; 
val x : int = 132 
# let f x = 
    let x = 15 in (let g x = print_int x) 150;; 
Error: Syntax error 

错误。为什么? (我只是想命名函数“g”,但语法错误?)

任何人都可以帮忙吗? THX

回答

3

为了解决语法错误,你就必须把它写这样的(你缺少in关键字和函数的名称):

let f x = 
let x = 15 in let g x = print_int x in g 150;; 

要理解为什么看你的第一个例子中的类型在顶层:

# (fun x -> print_int x);; (* define a function *) 
- : int -> unit = <fun> 
# (fun x -> print_int x) 150;; (* define a function and call it with 150 *) 
150- : unit =() 
# (let g x = print_int x);; (* define a value named 'g' that is a function , 'g' has the type below *) 
val g : int -> unit = <fun> 
# (let g x = print_int x) 150;; (* you can't do this, the code in the paranthesis is not a value: it is a let-binding or a definition of a value *) 
Error: Syntax error 

f xxlet x = 15什么都没有做与你的函数中的X,在最里面的范围x需要preceden (这被称为阴影)。

+0

Thx,很好的帮助! – user2170674