Thomas
Thomas

Reputation: 12107

What does the 'let {record} = object' syntax achive in F#?

with the following example:

type Person = {First:string; Last:string}
let alice = {First="Alice"; Last="Doe"}
let {First=first} = alice

what does the last let do exactly?

Upvotes: 3

Views: 115

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564383

The last let binding is a binding with a pattern match, specifically using a record pattern.

This creates a binding named first which will extract the First name from your record instance. In this case, first becomes bound to the value "Alice", and is usable in that scope.

To illustrate, you can add the following line after your code: printfn "%s" first, and you'll see "Alice" printed.

Note that let bindings allow any pattern - the spec is let identifier-or-pattern [: type] =expressionbody-expression, which allows you to work with lots of different patterns. This is useful in many cases, for example, if you have a tuple:

let t = (1, 2)
let (first, second) = t // Use a pattern to bind each tuple value by name
printfn "%i" second

Upvotes: 5

Related Questions