Sum data type: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added new task for creating a sum type)
 
(Converted to draft task (too early for 'full' task) and corrected typo.)
Line 1: Line 1:
{{task|Basic language learning}}
{{draft task|Basic language learning}}
{{Data structure}}
{{Data structure}}


Line 5: Line 5:
Create a sum data type:
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.
A sum data type 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.
Only one of the types can be in use at any one time.



Revision as of 16:00, 25 June 2019

Sum data type is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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 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>