Tech News
← Back to articles

Type-machine

read original related products more articles

Using Template Haskell to derive the structure of records and simulate structural subtyping

Type-machine

Code available on GitHub, package available on Hackage.

Introduction

In Haskell, we usually model data using algebraic data types, like this:

1 data Maybe a = Nothing | Just a

Here we defined a Maybe type, which has two constructors, Nothing and Just . The Just constructor has one argument, while Nothing as none.

It is common to consider these constructors’ arguments as fields, which can be mainly distinguished by their position in the constructor’s declaration. When data types have many fields, it becomes a bit of a pain to select them, for example, in functions like these:

1 2 3 4 5 6 7 8 9 10 data URL = URL String -- ^ Scheme String -- ^ Hostname Maybe Int -- ^ Port String -- ^ Path [( String , String )] -- ^ Query Parameters Maybe String -- ^ Fragment (#) getPath :: URL -> String getPath ( URL _ _ _ path _ _ ) = path

Thankfully, in GHC 7.4.1 was introduced the record syntax, which allows naming fields, like this:

... continue reading