41

I am just starting to learn F#. In several F# coding examples I see the keyword "in" used in the following way:

let doStuff x =
    let first, second = x in
    first + " " + second

The function works with and without the "in" at then end of the second line. What does "in" do?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jakob Christensen
  • 14,826
  • 2
  • 51
  • 81

3 Answers3

36

in is a hangover from F#'s OCaml roots and it specifies bound variables, which are subtly different to variable scopes.

Think of variable binding as follows; You have an expression:

first + " " + second

As it stands first and second are unbound - they don't have any fixed values - so that expression has no concrete value at present. By using

let (...) in

syntax you are specifying how those variables are bound in that expression, so your example will use variable substitution to reduce that function down to

let doStuff x =
  x + " " + x

In this example both forms are identical, but imagine the following:

let (x = 2 and y = x + 2) in
     y + x

This will not work the same as

let (x = 2 and y = x + 2)
     y + x

Because in the former case x is only bound after the in keyword.

In the later case normal variable scoping rules take effect, so variables are bound as soon as they are declared.

Hope that clears things up. In general you should always use the version without in and specify #light at the start of your F# source files

Mark Pim
  • 9,898
  • 7
  • 40
  • 59
  • 2
    I do not think the code in the question is equivalent to `let doStuff x = x + " " + x`. I believe it is equivalent to `let doStuff x = (fst x) + " " + (snd x)`. Am I wrong here? – Soldalma Feb 09 '17 at 01:59
  • 3
    Mark, this was long ago, but those examples don't work in F# and I think they may never have. Is this OCaml only syntax? Also, with "different", do you mean one compiles in OCaml, but the other doesn't? Because otherwise I don't see how they can have different results. – Abel Jun 10 '20 at 08:52
  • @Mark please edit this so people don’t waste time trying to understand it only to find that it is irrelevant in 2023. – silvalli Apr 06 '23 at 19:47
7

Here is another related thread here on SO that could be also useful:

Community
  • 1
  • 1
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
6

To quote from here.

When the light syntax option is enabled 'in' is optional. The token after the '=' of a 'let' definition begins a new block, where the pre-parser inserts an implicit separating 'in' token between each 'let' binding that begins at the same column as that token.

Without the light syntax option 'in' is very often required. The 'in' is optional when the light syntac option is used.

So I'm guessing you're using light syntax.

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900