Search⌘ K
AI Features

Nesting Custom Types

Explore how to define nested custom types in Haskell by extending basic shapes with location data. Learn to write functions that use nested pattern matching to handle these types, and implement shape manipulation such as moving a shape using vectors.

Defining nested types

When defining custom types with data, we are not limited to using predefined types in the constructors. We can also nest custom types.

Let’s extend our Geometry type (from the previous lesson) with location information. Remember, its definition was

data Geometry = Rectangle Double Double | Square Double | Circle Double deriving (Show)

The location of a shape should be the coordinates of its center point in the 2D plane. We thus identify a location by two doubles, its x and y coordinates.

data Coordinates = Coordinates Double Double deriving (Show)

Note that we are using Coordinates here as both the name of the type as well as the name of the only constructor. This is fine, as types and constructors have different namespaces. By convention, types ...