This is not a trivial question as it may appear at first sight. A pragmatic answer is that F# supports the OCaml syntax (2nd case) and the F# syntax (first sample). But the existence of the 'in' keyword has a deeper meaning whose roots are in mathematics.

With the 'in' keyword you are indicating that the x symbol is bound to the given expression in a specific context. This mean that the x symbol is bound only after the 'in' keyword. For example the following is wrong:

1
let x = 2 and y = x + 2 in y

Since the x symbol is not bound yet to the constant 2. This matehmatical notion of visibility leads to a code that is rather verbose, with a lot of nested lets that are rather annoying. The corresponding notion in progamming languages is the notion of scope of a variable, and we are accoustomed to the fact that a variable is visible after its definition in the block, so the light syntax in F# features a more modern syntax that reduces the verbosity of the full ML syntax, though retaining the essential traits.

In conclusion the two samples are the same, though the first is the F# way to do it :)

Antonio

By on 11/5/2007 1:00 AM ()

I see..

So in essence, the construct

1
2
3
4
let SimpleSample() =
   let x = 2 in 
   let y = x + 2 in
   let z = x * y

says that the value of x 'in' the function "x+2" is 2 and the value of y in "x * y" is "x + 2" , whereby ultimately the value of z is "2 * (2 + 2)"?

- Erik

By on 11/5/2007 10:52 PM ()

Pretty much, but more accurately: x is bound to the expression "2" in the expression "let y = x + 2 in let z = x * y", y is bound to the expression "x + 2" in the expression "let z = x * y" and z is bound to the expression "x * y" in the expression... well, there is a syntax error in your code here but you get the point.

In functional languages a let expression consists of three parts: the name of the variable to bind, the expression to bind it to, and the expression in which the variable is in scope. In abstract syntax you have

1
let var = expr1 in expr2

The keyword in simply serves as a marker to separate the two expressions it lies between (similar to how the equals sign separates the variable name and first expression). The presence of the in keyword makes the language very easy for a compiler to parse: it is like a big red flag that tells the parser that expr1 has ended and expr2 is about to start.

But having all these in's everywhere can be tedious for the programmer, so advanced languages like F# allow you to optionally omit the in keyword and let the compiler automatically work out where the in's should occur based on the indentation of your code.

By on 11/6/2007 5:18 AM ()

Great explanation guys! Thanks!

By on 11/6/2007 6:19 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper