Examples-0.1.0: Haskell code examples
Copyright© Frank Jung 2024
LicenseGPL-3.0-only
Safe HaskellSafe-Inferred
LanguageHaskell2010

PolyList

Description

From Thinking with Types, Sandy Maguire, 2021, section 5.3 Heterogeneous Types.

Source

See Thinking with Types for code and solutions to exercises.

Unable to Derive Functor for Hetereogeneous Lists

Unfortunately, for your PolyList type, it's not possible to create a Functor instance because PolyList is indexed by a type-level list of types, and Functor requires a type constructor of kind * -> *, i.e., a type constructor that takes exactly one type argument.

The PolyList type is a heterogeneous list that can contain values of different types, and the type of each value is encoded in the type of the list itself. This is fundamentally different from the concept of a Functor, which operates on homogeneous containers that contain values of a single type.

See also RankNTypes for other examples.

Synopsis

Types

data PolyList (ts :: [Type]) where Source #

A list that contain polymorphic types.

Constructors

PNil :: PolyList '[] 
(:#) :: t -> PolyList ts -> PolyList (t ': ts) infixr 5 

Instances

Instances details
All Show ts => Show (PolyList ts) Source # 
Instance details

Defined in PolyList

Methods

showsPrec :: Int -> PolyList ts -> ShowS #

show :: PolyList ts -> String #

showList :: [PolyList ts] -> ShowS #

All Eq ts => Eq (PolyList ts) Source # 
Instance details

Defined in PolyList

Methods

(==) :: PolyList ts -> PolyList ts -> Bool #

(/=) :: PolyList ts -> PolyList ts -> Bool #

(All Eq ts, All Ord ts) => Ord (PolyList ts) Source # 
Instance details

Defined in PolyList

Methods

compare :: PolyList ts -> PolyList ts -> Ordering #

(<) :: PolyList ts -> PolyList ts -> Bool #

(<=) :: PolyList ts -> PolyList ts -> Bool #

(>) :: PolyList ts -> PolyList ts -> Bool #

(>=) :: PolyList ts -> PolyList ts -> Bool #

max :: PolyList ts -> PolyList ts -> PolyList ts #

min :: PolyList ts -> PolyList ts -> PolyList ts #

data HEntry Source #

An alternate implementation of a heterogenous item. The HEntry type is an existential wrapper around a value of any type that has a Show instance. This allows us to store values of different types in a list, but we can't derive Eq or Ord for HEntry because the types are potentially different.

See also RankNTypes for other examples.

Constructors

forall a.Show a => HEntry a 

Instances

Instances details
Show HEntry Source # 
Instance details

Defined in PolyList

Functions

pLength :: PolyList ts -> Int Source #

Get the length of a polymorphic list.

pHead :: PolyList (t ': ts) -> t Source #

Get the head of a polymorphic list.