Chapter 2Using Types

In this chapter, you will learn how to create your own types, and how to use those types to structure your program.

Algebraic Data Types (ADTs)

Pattern Matching on ADTs

Plot a course for Planet Vulcan

> sqrt 2
1.4142135623730951
> 2 ** 3
8
distance :: (Double, Double) -> (Double, Double) -> Double
distance = \ (x1, y1) (x2, y2) ->
  sqrt ((x1 - x2) ** 2 + (y1 - y2) ** 2)

Volume of a planet. Earth has a mean radius of 6371 km. It has a mass of 5.97237e24 kg.

data Radius = Radius Double

data Mass = Mass Double

data Volume = Volume Double

data Density = Density Double

data Coordinates = Coordinate
  { coordinateX :: Double
  , coordinateY :: Double
  }

-- This is a comment

data Planet = Planet
  { planetName :: String
  , planetMass :: Mass
  , planetRadius :: Radius
  , planetCoordinates :: Coordinates
  }

volume :: Radius -> Volume
volume (Radius r) = Volume ((4 / 3) * pi * (r ** 3))

density :: Radius -> Mass -> Density
density (Radius r) (Mass m) = Density (m / (volume r) / 1e12)
> volume earthRadius
1.0832069168457535e12