Koopakiller
Koopakiller

Reputation: 2884

Best syntax for reusing (anonymous) record values

f is a function which returns a (anonymous) record, e.g.:

let f a b c =
    {| X = a + b; Y = c; Z = 1|}

What's the syntax to change an element based on its current value without asigning it to another binding before?

let x1 = {| f a b c with Y = Y + 12 |} 
//                           ^ The value or constructor 'Y' is not defined.

Especially in more complex situations, e.g.:

let x2 = if a + b < c 
         then {| X = a; Y = c + b; Z = 1 |}
         else {| f a b c with Y = Y + 12 |}
//                                ^ The value or constructor 'Y' is not defined.

I would like to see something like an alias. Does such a thing exist?

let x2 = if a + b < c 
         then {| X = a; Y = c + b; Z = 1 |}
         else {| (f a b c) as y with Y = y.Y + 12 |}
//                         ^^^^          ^^

Upvotes: 1

Views: 51

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

The exact syntax you're suggesting doesn't exist, but this is exactly what let does:

let x2 = if a + b < c 
         then {| X = a; Y = c + b; Z = 1 |}
         else let y = f a b c in {| y with Y = y.Y + 12 |}

In your question you say "without assigning it to another binding", but your last example does just that: it binds f a b c to y (which is why this is exactly what let does).

This makes me think that by "another binding" you meant something more specific than just a binding. Perhaps if you clarify what that is, and, more importantly, why exactly doesn't it work for you, we may come up with a better solution.

Upvotes: 3

Related Questions