liveBook · Manning

Algebraic data type

As explained in Learn Haskell by Example

An algebraic data type is a user-defined type formed from one or more named constructors, potentially carrying fields.

An algebraic data type encodes a set of named alternatives as one user-defined type. In a command-line tool, it gives each supported option a clear representation that later functions can inspect and use to choose behavior. section 1.1.1 section 4.4.1

Listing 4.12 Data type used for representing options for the line number program
data LineNumberOption
  = ReverseNumbering     #1
  | SkipEmptyLines        #2
  | LeftAlign              #3
  deriving (Eq)    #4

Defines three option constructors—ReverseNumbering, SkipEmptyLines, and LeftAlign—and derives Eq so options can be compared. section 4.4.1

A parser can convert ordinary strings into these constructors while using Maybe to represent failure. Once parsed, the options can influence control flow by selecting functions such as numberNonEmptyLines or numberAllLines. section 4.4.1

Listing 4.13 Function to parse normal strings into the new data type for options
lnOptionFromString :: String -> Maybe LineNumberOption
lnOptionFromString "--reverse"    = Just ReverseNumbering    #1
lnOptionFromString "--skip-empty" = Just SkipEmptyLines      #1
lnOptionFromString "--left-align" = Just LeftAlign           #1
lnOptionFromString _ = Nothing      #2

Maps recognized command-line strings to constructors and returns Nothing for unsupported options. section 4.4.1

How Learn Haskell by Example covers it

How deep it goes
Defines constructors and applies them in parsing, comparison, and function selection, while deferring a detailed treatment of deriving.
Examples
Uses line-numbering options for reversing numbering, skipping empty lines, and left-aligning output.
What you can do after
Build command-line option representations and parsers that select different line-numbering behaviors.
How it connects
Connects algebraic data types with type classes, monads, Maybe, higher-order functions, and pattern matching.

Also explained in

Compare how 5 books explain algebraic data type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.