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?
inis 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:
As it stands
firstandsecondare unbound – they don’t have any fixed values – so that expression has no concrete value at present. By usingsyntax you are specifying how those variables are bound in that expression, so your example will use variable substitution to reduce that function down to
In this example both forms are identical, but imagine the following:
This will not work the same as
Because in the former case
xis only bound after theinkeyword.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
inand specify#lightat the start of your F# source files