Scott Nimrod
Scott Nimrod

Reputation: 11595

Need more clarity on Definition Expressions

What does this statement mean and why would I write code like that?

let id x = x in (id 3, id "Three") 

F# 3.0 spec: 6.6 Definition Expressions

Upvotes: 0

Views: 75

Answers (3)

Petr
Petr

Reputation: 4280

It defines identity function:

let id x = x

in this expression:

(id 3, id "Three")

so result of this expression is a tuple of type (int * string):

(3, "Three")

Edit: You don't necessarily need to write code like this (maybe in very rare cases). By default F# uses light syntax without in like this:

let id x = x // Define the function
(id 3, id "Three") // Apply it to the elements of tuple

When you are using verbose syntax you don't have to follow whitespace indentation rules. Here it is described more clearly: http://fsharpforfunandprofit.com/posts/fsharp-syntax/

I believe verbose syntax is used mostly when you need to use let in a one line expression as in your sample

Upvotes: 3

nh2
nh2

Reputation: 620

If id x = x then a) id 3 = 3 and b) id "three" = "three". Put it together, in (id 3, id "three"), if we let id x = x then the result is that (id 3, id "three") = (3, "three"). That's the gist of it.

Upvotes: 1

Lee
Lee

Reputation: 144126

let v = expr in body

defines a new environment with the name v bound to expr and then evaluates body in the created environment. In this case id is defined to be a function of type a -> a which just returns its argument. The body

(id 3, id "Three")

is then evaluated with id bound to the above function.

Upvotes: 2

Related Questions