Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between discriminated Union types in F#

Tags:

f#

I'm reading about F# and looking at people's source code and I sometimes see

Type test =
   | typeone
   | typetwo 

And sometimes i see

type test = typeone | typetwo 

One of them has a pipe before and the one doesn't. At first I thought one was an enum vs discriminated Union but I THINK they are the same. Can someone explain the difference if there is any?

like image 637
Luke Xu Avatar asked Dec 08 '22 23:12

Luke Xu


1 Answers

There is no difference. These notations are completely equivalent. The leading pipe character is optional.

Having this first pipe optional helps make the code look nicer in different circumstances. In particular, if my type has many cases, and each case has a lot of data, it makes sense to put them on separate lines. In this case, the leading pipe makes them look visually aligned, so that the reader perceives them as a single logical unit:

type Large =
  | Case1 of int * string
  | Case2 of bool
  | SomeOtherCase
  | FinalCase of SomeOtherType

On the other hand, if I only need two-three cases, I can put them on one line. In that case, the leading pipe only gets in the way, creating a feeling of clutter:

type QuickNSmall = One | Two | Three
like image 133
Fyodor Soikin Avatar answered Dec 19 '22 16:12

Fyodor Soikin