简体   繁体   中英

OCaml Syntax Environment and Syntax Error

let x = 132;;
let f x = 
    let x = 15 in (fun x -> print_int x) 150;;
f 2;;

The output is 150.

My question is: why "print_int" does not perform yet? is that because fun x-> print_int x just defines a function, but not required to perform yet? Does the inside function just simply print 15?

I wanted to respond to my guess, and when I modify the code to this:

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

an error is prompted. Why? (I was just trying to name the function "g", but syntax error?)

Anyone can help? thx

To solve the syntax error you'd have to write it like this (you were missing the in keyword and the function's name):

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

To understand why look at the type of your first example in the toplevel:

# (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

The x in fx and let x = 15 have nothing to do with the x inside your function, the x in the innermost scope takes precedence (this is called shadowing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM