Thomas
Thomas

Reputation: 12107

conditional field in anonymous records, in f#

I often use anonmymous records to build on the go data that will eventually be serialized and returned to be consumed somewhere else. This is very flexible, quick to deal with, etc.

But one thing I'm really missing is the ability to do something like this pseudo code:

{|
    SomeData = 3
    StartTime = ....
    if ProcessedFinished then yield { EndTime = ... }
|} 

when I could add a field, or not, based on some conditions.

Is there a solution to have the flexibility of the anonymous record, yet have the ability to make conditions like this? I could do a dictionary, then insert values based on conditions but then I'd have to box all the values as well and it would be messy right away.

Upvotes: 1

Views: 154

Answers (1)

Phillip Carter
Phillip Carter

Reputation: 5005

What you're after is not possible today, but you can get pretty close like so:

let initialData =
    {|
        SomeData = 3
        StartTime = ....
    |}

if ProcessedFinished then
    {| initialData with EndTime = ... |}
else
    initialData

Of course, to represent this as a return type it's now more involved, as you'll likely need to use SRTP in the signature to account for any type with a SomeData and StartTime member on it. It's perfectly fine if this is just in the body of a routine that then produces another result to return, though.

If you want to represent data that may be optionally available based on a condition, especially if you want it to live outside of a given function, I'd recommend an option for that field instead.

Upvotes: 2

Related Questions