Monday 19 April 2021

Union Types | Discriminated Union vs Free Union With Example | PPL | Sebesta | Data Types

                   In this post, we will see Union Types | Discriminated Union vs Free Union With Example | PPL | Sebesta | Data Types in Programming Language | data types in ppl, data types ppl, elementary data types in programming language, ppl, sebesta, union types,discriminated union, union, tagged union, free union, discriminated vs free union   


8. Union Types

              A union is a type whose variables may store different type values at different times during program execution.

 

Record vs Union

 

struct sample

{

int x;

float y;

char z;

};

 

union sample

{

int x;

float y;

char z;

};

 

union sample x;

 

Free Unions vs Discriminated Unions

 

              C and C++ provide union constructs in which there is no language support for type checking.

              The unions in these languages are called free unions, because programmers are allowed complete freedom from type checking in their use.

 

 

union sample

{

int a;

float b;

};

union sample myunion;

float x;

 

myunion.a = 27;

x = myunion.b;

 

              Type checking of unions requires that each union construct include a type indicator. Such an indicator is called a tag, or discriminant, and a union with a discriminant is called a discriminated union.

              The first language to provide discriminated unions was ALGOL 68. They are now supported by Ada, ML, Haskell, and F#.

 

Unions in Ada

 

e.g.

type Shape is (Circle, Triangle, Rectangle);

type Colors is (Red, Green, Blue);

 

type Figure (Form : Shape) is

       record

              Filled : Boolean;

              Color : Colors;

              case Form is

                      when Circle =>

                             Diameter : Float;

                      when Triangle =>

                             Left_Side : Integer;

                             Right_Side : Integer;

                             Angle : Float;

                      when Rectangle =>

                             Side_1 : Integer;

                             Side_2 : Integer;

              end case;

       end record;

 

 

Figure_1 : Figure;

Figure_2 : Figure(Form => Triangle);

 

Here,

Figure_1 is unconstrained variant record.

Figure_2 is constrained variant record.

 

Unions in F#

 

type intReal =

| IntValue of int

| RealValue of float;;

 

 

A compile-time descriptor for a discriminated union

 

type Node (Tag : Boolean) is

       record

              case Tag is

                      when True => Count : Integer;

                      when False => Sum : Float;

              end case;

       end record;


 

 

 Watch following video:

 Watch on YouTube: https://www.youtube.com/watch?v=aXs4Ugvjwwc 

No comments:

Post a Comment