vik santata
vik santata

Reputation: 3109

How to understand specific F# syntax

At the end of this statement:

let (a,b,c) = (1,2,3) in printfn "%i,%i" a b;;

, there's

a b;;

What's the usage of the ending "a" and "b", are they parameter of some function call, or, are they a return value(tuple) of previous function? If so, what is the usage of let (a,b,c), I suppose it should define a tuple of 3 elements, but what does printfn do here in the statement?

In other words, how can I split this complex statement into several shorter statements that is easier to understand? I don't quit get "let ... in" semantics. Any explanations?

Thank you.

Upvotes: 0

Views: 104

Answers (2)

latkin
latkin

Reputation: 16812

The in keyword groups together intermediate bindings into a single expression, as opposed to a more imperative-style sequence of distinct statements. OCAML (from which F# derives) requires this expression-oriented syntax in many cases. F# allows for a more statement-oriented structure.

You can think of it as the difference between these different (but equivalent) ways of describing your program in English:

  • "In the following, let a = 1 and b = 2: Print 'a,b' to the console" (expression style - intermediate bindings are just "leading up" to the final expression body)
  • "Set a to 1. Then set b to 2. Then print 'a,b' to the console." (statement style - each step is distinct and there is less sense that it all groups together)

The latter phrasing would correspond to the following code, which does the same thing as your original:

let a = 1
let b = 2
printfn "%i,%i" a b

[note - Carsten's answer is great wrt the de-tupling and the unused c, so I just focused on in]

Upvotes: 1

Random Dev
Random Dev

Reputation: 52300

let (a,b,c) = (1,2,3) in ... means: inside ... a should have value 1, b should have value 2 and c should have 3 (and those bindings will only exist inside the ... body - it's all one expression - the result will be whatever the result of ... is)

To do this the tuple (1,2,3) get destructed with into the pattern (a,b,c)

now in side ... is printfn "%i,%i" a b - printfn "%i,%i" gets compiled into a function that takes two integers (in curried form) and prints them out (with a , between them).

As you can see you call this function with the arguments a and b (remember those values from above).

Overall you will print out 1,2

the c get`s ignored so another way of writing it would be

let (a,b,_) = (1,2,3) in printfn "%i,%i" a b

Upvotes: 12

Related Questions