Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a Discriminate Union vs Record Type in F#

Tags:

I am trying to get the basics of F# clear before moving on to complex examples. The material I'm learning has introduced both Discriminate Unions and Record types. I have reviewed the material for both, but it is still unclear to me why we would use one over the other.

Most of the toy examples I have created seem to be implementable in both. Records seem to be very close to what I think of as an object in C#, but I am trying to avoid relying on mapping to c# as a way to understand F#

So...

  • Are there clear reason to use one over the other?

  • Are there certain canonical cases where one applies?

  • Are there certain functionalities available in one, but not the other?

like image 552
Chris Tarn Avatar asked Jun 25 '13 07:06

Chris Tarn


1 Answers

Think of it as a Record is 'and', while a discriminated union is 'or'. This is a string and an int:

type MyRecord = { myString: string                   myInt: int } 

while this is a value that is either a string or an int, but not both:

type MyUnion = | Int of int                | Str of string 

This fictitious game can be in the Title screen, In-game, or displaying the final score, but only one of those options.

type Game =   | Title   | Ingame of Player * Score * Turn   | Endgame of Score 
like image 99
Robert Jeppesen Avatar answered Dec 28 '22 22:12

Robert Jeppesen