user2170674
user2170674

Reputation: 41

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

Upvotes: 1

Views: 593

Answers (1)

user2299816
user2299816

Reputation:

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 f x 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).

Upvotes: 3

Related Questions