Lesson 33. Capstone: SQL-like queries in Haskell

 

This capstone covers

  • Using the Monad type class to create SQL-like queries on lists
  • Generalizing functions written for one Monad (for example, List) to many
  • Organizing functions with types

In the preceding lesson, you saw how List as a Monad can also be understood as a list comprehension, which is used heavily in Python. In this capstone, you’re going to take your use of lists and monads one step further to create a SQL-like interface to lists (and other monads). SQL is used as the primary means to query relational databases. It has a clean syntax for representing the relationships between data. For example, if you had data about teachers teaching classes, you could query the teachers teaching English like this:

select teacherName from
teacher inner join course
on teacher.id = course.teacherId
where course.title = "English";

This allows you to easily combine two data sets, the teacher table and course table, to extract relevant information. You’ll build a set of tools you’ll call HINQ (borrowing its name from the similar .NET tool LINQ). HINQ will allow you to query your data relationally. You’ll make extensive use of the Monad type class to make this possible. In the end, you’ll have a query tool that

  • Provides a familiar interface for querying relational data in Haskell
  • Is strongly typed
  • Uses lazy evaluation to allow you to pass around queries without executing them
  • Can be used seamlessly with other Haskell functions

33.1. Getting started

33.2. Basic queries for your list: select and where

33.3. Joining Course and Teacher data types

33.4. Building your HINQ interface and example queries

33.5. Making a HINQ type for your queries

33.6. Running your HINQ queries

Summary