sum-type-boilerplate

Library for reducing the boilerplate involved with sum types

https://github.com/jdreaver/sum-type-boilerplate#readme

Version on this page:0.1.0
LTS Haskell 19.33:0.1.1
Stackage Nightly 2022-03-17:0.1.1
Latest on Hackage:0.1.1

See all snapshots sum-type-boilerplate appears in

MIT licensed and maintained by David Reaver
This version can be pinned in stack with:sum-type-boilerplate-0.1.0@sha256:430b5ef908a810de26d2038715f1ee60c654d237c297600da89873c25be902ab,1641

Module documentation for 0.1.0

Used by 1 package in nightly-2017-07-04(full list with versions):

sum-type-boilerplate: A Haskell sum type library

CircleCI

This library allows users to use Template Haskell to easily construct and manipulate sum types. It was born out of the author’s desire to reduce the boilerplate associated with sum types while keeping the type safety they provide.

Sum Types

A sum type (also called a tagged union) looks like this in Haskell:

data MySum
  = MySumTypeA TypeA
  | MySumTypeB TypeB
  | MySumTypeC TypeC

Constructing this when you have a large number of types can be error-prone if you intend to have a uniform naming scheme, and if you intend to only have each type present once.

If you have many sum types with overlapping sets of types, then functions to convert between them can be full of boilerplate.

data OtherSum
  = OtherSumTypeA TypeA
  | OtherSumTypeB TypeB

otherSumToMySum :: OtherSum -> MySum
otherSumToMySum (OtherSumTypeA typeA) = MySumTypeA typeA
otherSumToMySum (OtherSumTypeB typeB) = MySumTypeB typeB

mySumToOtherSum :: MySum -> Maybe OtherSum
mySumToOtherSum (MySumTypeA typeA) = Just $ OtherSumTypeA typeA
mySumToOtherSum (MySumTypeB typeB) = Just $ OtherSumTypeB typeB
mySumToOtherSum other = Nothing

The boilerplate in examples isn’t too bad, but consider writing this when your sum type has dozens of types in it!

Where does this library come in?

Using sum-type-boilerplate, you can reduce all of the previous code into the following:

constructSumType "MySum" defaultSumTypeOptions [''TypeA, ''TypeB, ''TypeC]
constructSumType "OtherSum" defaultSumTypeOptions [''TypeA, ''TypeB]
sumTypeConverter "otherSumToMySum" ''OtherSum ''MySum
partialSumTypeConverter "mySumToOtherSum" ''MySum ''OtherSum

More features

  • This library has an extremely simple implementation. (In fact, it is useful as an example if you are learning template-haskell for the first time.)
  • The only dependency is on template-haskell. That means adding it as a dependency probably doesn’t introduce transitive dependencies.
  • The template haskell used here just produces vanilla Haskell data types. No crazy type-level magic is going on. That means if you want to ditch this library later on, just copy the generated code into your project.

Changes

sum-type-boilerplate Changelog

0.1.0

  • Initial release. Includes a TH function to create a sum type and two TH functions to convert between sum types.