F#: Ways to retrieve a value from a Single Case Discriminated Union

Intro

As I document my journey of learning F#, I have identified alternative methods for retrieving a value from a single case Discriminated Union.

Let’s examine the following code:

module SomeModule

type Email = Email of string

let email = Email "scott@abc.com"

With the code above, how can we retrieve the actual email address?
I have identified various approaches (i.e. syntax) to accomplish this task.

Method #1:

let address1 = match email with
               | Email v -> v

The code above is what I’m use to seeing as an example. However, it feels a bit overkill.

Method #2:

let address2 = email |> function
               | Email v -> v

The code above is less verbose than method #1. However, it still requires two lines of code.

Method #3:

let address3 = email |> function Email v -> v

The code above has been consolidated to just one line. However, that one line still feels a bit cryptic.

Method #4:

let (Email address4) = email

The code above is simple and somewhat concise. But it can be even shorter…

Method #5:

let Email address4 = email

The code above appears to be the most concise.

Conclusion

In conclusion, as I document my journey of learning F#, I have identified alternative methods for retrieving a value from a single case Discriminated Union. The End.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: