8. Overview

A walkthrough of the main ideas.

Some examples in this chapter assume you are familiar with Data.Set and Data.Map. You should ignore them on a first reading if they are unfamiliar.

  • Types must start with capital letters. A type can be called Dinosaur but not dinosaur.

  • Type synonyms, also known as type aliases.

      type BasicPoint = (Float, Float)
    
  • Use Data to create new data types. Here is a Point data type:

      data Point = Point Float Float
      getX (Point x y) = x
    
  • Use deriving to have an automatic simple output format and equality operation.

      data Point = Point Float Float deriving (Show, Eq)
    
  • choices using |

      data Point2D = Point2D Float Float deriving (Show, Eq)
      data Point3D = Point2D Float Float Float deriving (Show, Eq)
      data AbstractPoint = Point2D | Point3D
    
  • Named fields, like a Racket struct or Python’s @dataclass or perhaps just namedtuple.

      data Circle =
          Circle { center :: Point2D, radius :: Float }
              deriving (Show, Eq)
    
  • Named fields make it easy to update. Using {...} after the name of a variable makes a copy and only changes the fields listed.

      p = Point2D 20.0 50.0
      c = Circle {center=p, radius=16.0}
      q = p{x=30.0} -- new x, same y=50 that pp had
      d = c{center=q} -- new center, same radius as c
    
  • Danger: if the same field names are used in different records, enable the extension DisambiguateRecordFields by adding the following code at the start of your file.

      {-# LANGUAGE DisambiguateRecordFields #-}
    
  • Either a b = Left a | Right b. Read about it in the chapter.

Typeclasses 102

This part of the chapter contains some challenging material.

  • Making your new data type an instance of existing typeclasses, like Eq, Show, or Ord.

  • Creating a new typeclass using class (MyThing a) where ...

  • Building on existing types using instance (Eq a) => Eq (Maybe a) where

  • (class YesNo and instance YesNo [a] where ...) Making your own typeclass.

  • Functor: Yikes, start reading the text!! Memorize the typeclass rules for Functor.

  • Discovering kinds using :k. Abstract! Read.

  • The note at the end: “you don’t have to understand everything we did here…”. Take that seriously.

Explanations: type vs data

  • type

    These are just alternative names for the type on the right side of the equals sign. If a function that has an output of a BasicPoint, that output can be used as an input that is declared to require (Float,Float). These types are considered the weakest to use.

  • data

    These are stronger types because you cannot use a Point in a place where a type with a different name is required, even if both contain two Floats.

Last modified October 19, 2023: Material and projects using data types. (c6e0063)