sumanas27 / algebraic-in-java

A walkthrough of algebraic data types in Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Algebraic data types

Duke with Green Board

Algebraic data types (ADTs) were introduced in Hope, a small functional programming language developed in the 1970s at the University of Edinburgh.

Algebraic refers to the property that an ADT is created by algebraic operations. The algebra here, is sums, products and patterns:

sum

alternation (for three values A, B, C → A or B or C but not any combination or other subset).

product

combination (for three values A, B, C → A and B and C, possible to hold empty for one or more).

Algebraic data types are also known as composite types - a type formed by combining other types.

Algebraic data types (ADTs) can be identified and analyzed using Pattern Matching.

A deeper look at Sum and Product types

Let us look at the two common types: sum types and product types.

Values of algebraic types

Table 1. Deeper look at the algebraic data types
Sum Types Product Types

Use

Define variants

Hold Values

Logic

Logical OR operation (only one of the variants is possible)

Logical AND operation (combination of several values)

Content

Each variant can have its own constructor with specified number of arguments

Contains several values of possibly different types themselves

Examples

Enums (additional data cannot be associated with an enum, once created)

Class

Optional

Tuple (developer created/third party libraries)

Sealed types

Records (Java 14,15) Java 16

Visitor

Examples

Sum types

Table 2. Examples of Sum Types
Example Description

Example1Enum

Enums in Java

Example2Optional

Using Optional in Java

Example3Sealed

Sealed Types in Java

Product Types

Table 3. Examples of Product Types
Example Description

Example1Class

A Class in Java

Example2Tuple

Tuples in Java

Example3Record

Records in Java

Table 4. Examples of patterns used in Algebraic Java
Example Description

Example1Variance

Covariance and Contravariance

Example2VisitorPattern

A walk-through of the visitor pattern

Project Structure

|____LICENSE
|____README.adoc       <----- This file
|____assets            <----- Images linked above
|____src
| |____none
| | |____cgutils
| | | |____algebraic
| | | | |____sum       <----- Examples of Sum types
| | | | |____product   <----- Examples of Product types
| | | | |____other     <----- Examples of patterns

About

A walkthrough of algebraic data types in Java

License:MIT License


Languages

Language:Java 100.0%