Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

.net - Meaning of keyword "in" in F#

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...