Sum data type

From Rosetta Code
Revision as of 08:22, 25 June 2019 by rosettacode>Eterps (Added new task for creating a sum type)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Sum data type
You are encouraged to solve this task according to the task description, using any language you may know.

Data Structure
This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.


Task

Create a sum data type:

A sum data type is is a data structure used to hold a value that could take on several different, but fixed, types. Only one of the types can be in use at any one time.

Sum data types are considered an algebraic data type and are also known as tagged union, variant, variant record, choice type, discriminated union, disjoint union or coproduct.

Related task
See also




OCaml

<lang ocaml>type tree = Empty

         | Leaf of int
         | Node of tree * tree

let t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))</lang>

Rust

<lang rust>enum IpAddr {

   V4(u8, u8, u8, u8),
   V6(String),

}

let home = IpAddr::V4(127, 0, 0, 1);

let loopback = IpAddr::V6(String::from("::1"));</lang>