© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2025
A. Antich Magical Haskell https://doi.org/10.1007/979-8-8688-1282-8_2
2. Type Construction
Anton Antich 1
(1)
Schaffhausen, Schaffhausen, Switzerland
You got to “Nobu” right on time, barely past seven. As you were approaching the hostess, a hurricane of a girl ran into you – “Thank goodness you got here on time, Curry!” Curry, that must be my name? But why? I don’t even like curry?! Must be a different reason … – grabbed your hand, and dragged you past the busy tables somewhere deep in the restaurant, through the kitchen, out the back door, down the stairs, and into a dimly lit room. In the middle of the room stood a card table – green cloth, some barely visible inscription that spelled “Monoid” in golden letters on it – surrounded by six massive chairs that looked really old. The girl abruptly stopped, turned around, looked you right in the eye – hers were green – and asked almost irritably, but with a pinch of hope in her voice:
-
Well? Are you ready ?
-
Ahem … Ready for what?! Can you explain what’s going on?
-
Did you hit your head or something? And where were you last week? I called like 27 times! And why do you smell like manure? Did you suddenly decide to visit a farm?! Oh, the exploding horse, right … Ah, no time for this!
She dragged you to the table and pushed you into one of the chairs – she was strangely strong despite being so miniature – so that you had no choice but to sit. BOOM! Suddenly, a small firework exploded in your eyes, and you felt more magic coming back to you.
Out of thin air, you create a new deck of cards with intricate engravings on their backs, nothing short of a work of art. You feel them – they are cold and pleasant to touch – but then rest your hands on the table, close your eyes, and … It’s as if the cards became alive and burst in the air above the table, shuffling, flying around, dancing. You open your eyes, enjoying your newly mastered power over cards, and barely nod your head, and the deck, obeying your wishes, forms into a fragile house of cards right beside the Monoid sign.
You turn to look at your mysterious companion. She is smiling and there are twinkles in her eyes.
House of Cards with a Little Help from Algebra
Looks like our mage is making friends and remembering new spells, this time without risking any animal’s well-being. Let’s follow in his footsteps and learn some card magic !
First, download this chapter’s code from GitHub and try dealing some cards. You’ll see some beautiful (well, not as beautiful as the ones Curry created, but still …) cards being dealt – 9♥ 10♥ J♥ Q♥ K♥ A♥ – with barely more than 20 lines of code. Let’s understand what’s going on here step by step.
To start doing card magic – or card programming for that matter – we also need to create a deck of cards out of thin air. Here’s one way of doing it in Haskell:
-- Simple algebraic data types for card values and suites
-- First, two Sum Types for card suites and card values
data CardSuite = Clubs | Spades | Diamonds | Hearts deriving (Eq, Enum)
data CardValue = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Eq, Enum)
-- Now, a Product Type for representing our cards:
-- combining CardValue and CardSuite
data Card = Card CardValue CardSuite deriving(Eq)
We have created three new types above. CardSuite is inhabited by four values, Clubs, Spades, Diamonds, and Hearts – just like Int is inhabited by 2^64 values – that correspond to playing card suites. CardValue is inhabited by 13 values that represent card face values. All of it is pretty self-explanatory. Type Card represents a specific card and is a little bit more interesting – here we are combining our two existing types into one new type. Don’t mind the deriving statements for now – we’ll explain them down the road. Suffice it to say that here Haskell automatically makes sure we can compare values of these types ( Eq ) and that we can convert them to numbers ( Enum ).
Open REPL linked above again, run it (if you don’t run it first, you’ll get an error as the types won’t be loaded into the interpreter), and then play with these types on the right:
> let val = Jack
> val
\=> J
> let suite = Spades
> suite
\=> ♠
> let card = Card Ace Hearts
> card
\=> A♥
> let card1 = Card val suite
> card1
\=> J♠
Here we bound val to CardValue Jack and suite to CardSuite Spades and created two cards – Ace of Hearts directly from values and Jack of Spades from our bound variables – both approaches are perfectly valid. Create some other cards in REPL to practice.
Looking at the types’ definition above, the syntax for type creation should become apparent: to create a new type in Haskell, we write data <Name of Type> = <Name of Constructor1> <Type of value 11> ... <Type of value 1n> | <Name of Constructor2> <Type of value 21> ... <Type of value 2m> | ... . You can read symbol “|” as “or” – it is used for combining different types together into a new sum type , values of which can be taken from a bunch of different types we are combining, but every value is taken from only one of them. Types like data Card = Card CardValue CardSuite are called product types , and every value of such type contains values of all of the types we are combining.
EXERCISE
Now that you know how to define new types, think about how you would add a Joker card to your Card type? Amend the data Card = ... definition accordingly.
Important
The type name and constructor name do not need to be the same; you could have defined our Cards type, for instance, as data Cards = Card CardValue CardSuite. However, when you define a type that has only one constructor, it often makes sense to use the same name as we did above.
Algebraic Data Types
Sum and product types together are called algebraic data types , or ADTs in short ( which may be confused with abstract data types that are quite a different matter, but we will call algebraic types ADTs ), and they form a foundation of any modern type system.
Understanding ADTs is extremely important in Haskell programming, so let’s spend more time discussing them and looking at different ways to define them. Here are several more examples.
Type Person contains their name and age: data Person = Person String Int . We are combining a String to represent a name and an Int to represent an age, and then we can create people like so: Person "Curry" 37 or Person "Jane" 21 . This is a product type .
What if we wanted to represent built-in JavaScript types in Haskell – String, Number, Date, Object, etc.? Here is one way of doing it (it does not allow us to represent everything; we will look at the full JavaScript value type definition once we learn recursion):
data JSValues = JString String | JDate Int | JNumber Double | Undefined
Now, this is interesting – we have combined three types that “store” a String, an Int, and a Double inside a constructor and added a simple value “Undefined” as the fourth possible value. It means that values like JString "hello world" , JDate 12345225 (which is quite a long time ago), JNumber 3.141 , and Undefined are all valid values of the type JSValues . This is a sum type (see Figure 2-1 for representation of the types discussed).
A diagram with three main blue circles labeled "String," "Int," and "Double," each containing different data points. The "String" circle includes words like "Curry," "Mary," "ABC," "Hello," and "bitcoin." The "Int" circle contains numbers such as 1, 29, 3, 47, and 19874. The "Double" circle lists decimal numbers like 1.08, 22.9, 3.1415926, 47.0, and 293.443. Two arrows labeled "p1" and "p2" point from a top circle labeled "Person: Product" to the "String" and "Int" circles. Another arrow labeled "JSValues: Sum" points from a circle containing "JString 'Hello'," "JNumber 18.4," "Undefined," and "JDate 1948504" to the "Double" circle.
Figure 2-1
Sum and product types
By now, you should get a pretty good feel on what sum and product types are. When you create a product type, you combine values of several different types in one value, represented as a tuple (x_1:t_1, x_2:t_2, ... ) . When you create a sum type, each value of your type can be from a different type, but only one.
Practice creating types for different tasks you would be interested in solving.
Records
What if you wanted to extend the type Person to include more information about a person , which would be much more useful in a real-world situation? For example, place of birth, parents, first and last names, education, address, etc. If you had to write something like
data Person = Person String String Int Date Address Person Person
jane = Person "Jane" "Doe" 25 (Date 12 10 1992) addr father mother
it would be extremely confusing to use – you’d need to remember the order of fields, you’d confuse fields with the same types, etc. Thankfully, Haskell supports records – basically, a product type with named fields. We can define our Person type properly like this:
data Person = Person
{
firstName :: String
, lastName :: String
, age :: Int
, dob :: Date
, address :: Address
, father :: Person
, mother :: Person
}
-- you can still initialize a record just by applying a Constructor ('Person') to a bunch of values in order
jane = Person "Jane" "Doe" 25 (Date 12 10 1992) addr mother father
-- ... or, you can access the record's fields separately by their respective names
janesSister = jane { firstName = "Anne", age = 17, dob = Date 1 1 2000 }
PERSON EXERCISE
The type Person defined above has a problem – the “father” and “mother” fields create a recursion, which we have no way to terminate. Can you think how to solve this problem using sum types? If not, read the next section about Maybe, and it should give you an idea.
Heads Up
Records are in fact one of the biggest problems in Haskell right now due to somewhat inconvenient syntax. There are solutions in the form of a couple of libraries, such as lenses, and there’s active discussion on how to improve record handling in the future. But despite those syntactic inconveniences, they are fully functional records that are actively used in real-world programs.
Before we move on to the other ways of constructing new types, here is yet another example, which illustrates how product and sum types work together. Let’s say we want to model different two-dimensional geometric shapes. We can define the following product types :
data Point = P Double Double -- x and y
data Circle = C Double Double Double -- x and y for the center coordinates, radius
data Rectangle = R Double Double Double Double -- x and y for the top left corner, width and height
Now, let’s say we want a function that calculates the area of our shapes. We can start like this:
area :: Rectangle -> Double
area (R x y w h) = w * h
-- since we are not using x and y values from our Rectangle to calculate the area, we can omit them in
-- our pattern match like so:
area (R _ _ w h) = w * h
This works fine. But we need to calculate the area of circles as well and potentially other shapes . How do we do it? If you try to define another function area :: Circle -> Double , the typechecker will complain because you already have a function named area that has a different type. So what do we do? Create a differently named function for every type? Now, that would be ugly!
SHAPES EXERCISE
Think about how you would amend our types’ definitions to make the function area polymorphic. Don’t read further before you do!
There are several approaches to solving this. ( This is actually one of the problems with Haskell – you can solve one task in many different ways, and there’s just so much power and flexibility that sometimes it is getting overwhelming, and not just for beginners. We will see many examples of this down the road. ) One of them is using typeclasses or even type families (probably an overkill in this case) – we’ll get there soon. But now we will simply use a sum type. We can combine three of our shapes (product types) into one sum type. There are actually two ways to do it! The first one is if we want to keep Rectangle, Circle, and Point as separate concrete types in our system. Then we will use the definition above and will combine them into one type like so:
data Shapes = PointShape Point | CircleShape Circle | RectangleShape Rectangle
Then, our area function can be defined as follows with the help of pattern matching:
-- notice the type signature change:
area :: Shapes -> Double
-- we don't care about the point coordinates, area is always 0
area (PointShape _) = 0
-- notice the nested pattern match below:
area (CircleShape (C _ _ r)) = r * r * pi
area (RectangleShape (R _ _ w h)) = w * h
Now everything will work like a charm. When you write somewhere in your code area myShape , it will check what exact shape myShape is – Point, Circle, or Rectangle – and will choose the respective formula .
An alternative way to achieve the same result is to define the Shapes type directly as a sum type like so:
data Shapes = Point Double Double | Circle Double Double Double | Rectangle Double Double Double Double
I leave the area function definition for this case as an exercise. The difference from the previous approach is that in this case you will not have types Point, Circle, and Rectangle in your type system – they are simply constructor functions now. So trying to define a function from Rectangle to Double will be a typechecker error.
Using sum and product types, you can express a lot of real-world modeling already, but why stop there? We want to be even more efficient and polymorphic! Read on.
Type Functions Are Functions, Maybe?
Let’s spend some time reviewing a statement we made in the last chapter: type and data constructors are functions . This is extremely important to understand and internalize, so that you do not become confused when writing real-world programs that use monad transformer stacks and similar concepts that may look overwhelming, but are in fact quite simple. You need to be able to easily read type signatures and understand their structure at first glance. This is the key to mastering Haskell.
Let’s look at a couple of types, renaming type names now to distinguish between types and constructors: data Cards = Card CardValue CardSuite and data People = Person String Int . The part on the left is the name of the type , and the part on the right is the name of the data constructor and types of the values that this constructor contains. So, in reality, Card is a function that should be read in Pascal-ish pseudocode as function Card (x:CardValue, y:CardSuite) : Cards , i.e., it’s a (constructor) function from two variables, one of type CardValue and another of type CardSuite, that returns a value of type Cards! Same with Person , which turns into function Person (x:String, y:Int) : People .
In fact, using so-called GADT (generalized algebraic data type ) Haskell notation, this becomes even more apparent – below is the solution to the task of extending Card type with the Joker card written first with the familiar syntax and then using GADT:
data Cards = Card CardValue CardSuite | Joker
-- same using GADT
data Cards where
Card :: CardValue -> CardSuite -> Cards
Joker :: Cards
Looking at the second variant, the point about Card and Joker being functions becomes much clearer. In effect, it tells us that we are defining type Cards , which contains two constructors: Card , which takes two arguments of types CardValue and CardSuite and returns a value of type Cards , and Joker , which takes no arguments (or, strictly, an empty type – ()) and is a value of type Cards .
We can take it one step further and take the analogy of product and sum types to its fullest – we can treat the type Cards as a type function that is a sum of two product types: typeFunction Cards = Card (x : CardValue, y : CardSuite) + Joker() ! Of course “+” here has nothing in common with arithmetic sum but has the same meaning as “|” in actual Haskell syntax.
So Card is a constructor that creates a value of type Cards from two other values, and Cards , even though we just called it a type function , is in fact a “type constant.” It is a concrete type – you cannot apply it to another type and construct a new one. Unlike type function List that we hinted at in the last chapter, which actually creates new types from other types and as such is much more interesting and important for us. We’ll get to it in the next section, and we’ll need to understand it to follow along our card dealing program further.
For now, let’s start with the simplest real (non-constant) type function, one that constructs new types from other types: Maybe , which is used ubiquitously in Haskell :
data Maybe a = Just a | Nothing
-- in GADT syntax:
data Maybe a where
Just :: a -> Maybe a
Nothing :: Maybe a
Diagram illustrating the concept of "Maybe Int" and "Int." The top circle labeled "Maybe Int" contains "Just 1," "Just 3," "Just 29," "Just 47," "Just 19874," and "Nothing." An arrow labeled "Maybe a" points downward to the bottom circle labeled "Int," which contains the numbers "1," "3," "29," "47," and "19874." The notation above is very often a source of confusion for beginners and even advanced Haskell students – we are using variable "a" on both sides of the type definition, but they mean very different things on the left and on the right! In fact, this confusion should be cleared if you read this sort of definition in the spirit of what we’ve described above: typeFunction Maybe (a : Type) = Just (x : a) + Nothing () .
Please dwell on it until you fully understand the issue – it will save you lots of hours of frustration with more complex types down the road. We are in effect saying here: Maybe is a type function that takes a type variable “a” and creates a new type from it (“Maybe a”) with the help of two constructor functions – “Just,” which takes a “regular” variable of type a and creates a value of type “Maybe a,” and “Nothing,” a function of zero arguments that is a value of type “Maybe a.” So “a” is a variable of type “Type” – it can take a value of any Type we defined – on the left, and it is used in the type signature for constructor function “Just” variable on the right.
Take a breath and let it sink in.
Why is the type (which really is a type function) Maybe a useful? It’s the easiest way to handle failure in your functions. For example, you could define a function divide like so:
divide :: Double -> Double -> Maybe Double
divide x 0 = Nothing
divide x y = Just (x / y)
This function would return Nothing if you try to divide by zero , instead of crashing or throwing an exception, and Just <result of division> if you divide by non-zero. This is a trivial example, but Maybe is of course very useful in thousands of other more complex situations – basically, anywhere you need to handle the possibility of failure, think about Maybe (there are other ways to handle failure and errors in Haskell as we shall see further on).
Note also function definition syntax – a very powerful and concise pattern matching approach. Under the hood, this definition translates into something like
divide x y = case y of
0 -> Nothing
_ -> Just (x/y)
…but in Haskell you can avoid writing complex nested case statements and simply repeat your function definition with different variable patterns, which makes the code much more readable and concise.
So what if we also have a function square x = x * x that works on Doubles and need to apply it to the result of our safe divide function? We would need to write something like
divideSquare x y = let r = divide x y in
if r == Nothing then 0
else <somehow extract the value from under Just and apply square to it>
To do the “somehow extract” part in Haskell, we again use pattern matching, so the function above would be written as
-- function returning Double
divideSquare x y = let r = divide x y in
case r of Nothing -> 0
Just z -> square z
-- or, better, function returning Maybe Double as returning 0
-- as a square of result of divide by zero makes no sense
divideSquare x y = let r = divide x y in
case r of Nothing -> Nothing
Just z -> Just (square z)
We pattern-match the result of divide and return Nothing if it’s Nothing or Just square of the result if it’s Just something . This makes sense, and we just found a way to incorporate functions that work between Doubles into functions that also work with Maybe Doubles. But come on, is it worth such a complicated verbose syntax?! Isn’t it better to just catch an exception once somewhere in the code and allow for division by zero?
Yes, it is worth it and, no, it’s not better to use exceptions, because you can rewrite the above as simply divideSquare x y = square <$> divide x y , or looking at all the function definitions together :
square :: Double -> Double -> Double
square x = x * x
-- safe divide function
divide :: Double -> Double -> Maybe Double
divide x 0 = Nothing
divide x y = Just (x / y)
-- our function combining safe divide and
divideSquare :: Double -> Double -> Maybe Double
divideSquare x y = square <$> divide x y
-- compare with the same without Maybe:
divide' x y = x / y -- will produce an error if y is 0
divideSquare' :: Double -> Double -> Double
divideSquare' x y = square $ divide' x y
Wow. Isn’t it great? We are using practically the same syntax for both unsafe functions between Doubles and safe functions between Maybe Doubles, and what’s more, we can use the same approach for a lot of other different type functions, not just Maybe a .
Here, operator $ is just function application with lowest precedence, so allows to avoid brackets – without it you’d write square (divide' x y) – and <$> is another operator that also applies functions defined for concrete types, but it does so for values built with a special class of type functions from these types, e.g., Maybe a or List a , without the need to write nested case statements. It is a key part of something called a Functor in both Haskell and Category Theory, and we will look at it in more detail in the next chapter.
In the end, it’s all about making function composition easy but safe – remember Chapter 1 and how to think about solving problems functionally? You break the problem down into smaller parts and then compose functions together, making sure input and output types “fit together.” All the complicated scary terms you may have heard or read about in Haskell – Functors, Monads, Arrows, Kleisli Arrows, etc. – are all needed (mostly) to make composing different functions easy, safe, and concise, which, in turn, makes our task to decompose a problem in smaller pieces so much more easy and enjoyable. So don’t be scared, it will all make perfect sense.
FIXING PERSON EXERCISE
Think about some problems you had solved using exceptions in imperative languages that you may solve more elegantly using Maybe. Modify the type “Person” so that you can store information about children, which may or may not exist, for a person.
Advanced: On Data Constructors and Types
It pays to understand how Haskell (GHC specifically) treats and stores values of different types. One of the powerful features of Haskell is that it is a statically typed language – which means there is no type information available at runtime! This leads to much better performance with at the same time guaranteed type safety, but is a source of confusion for many programmers coming from the imperative background.
Let’s look at the type Person we defined above, changing the names a bit to avoid confusion :
data Person = PersonConstructor String Int
-- or, in a clearer GADT syntax:
data Person where
PersonConstructor :: String -> Int -> Person
The name of the type is Person, and it has only one data constructor called PersonConstructor that takes an Int and a String and returns a “box” of them that has a type Person . Technically, it creates a tuple (n :: String, a :: Int) – so, for instance, when you write something like john = PersonConstructor "John" 42 , you get a tuple ("John", 42) :: Person . The beauty of Haskell is that during the typechecking stage, the compiler has only one job – make sure your functions compose , i.e., input types to all the functions correspond to what the function expects, and the output type of whatever the function’s body produces corresponds to what is expected in the type signature as well. Once this check is done, all the type information gets erased – it is not needed, as we have guaranteed and proved it mathematically that every function will receive correct values at runtime. This immensely increases performance. That’s why they say “if it compiles, it works” about Haskell programs.
So, if you have a function showPerson :: Person -> String that is defined something like showPerson (PersonConstructor name age) = name ++ " is " ++ show age ++ " years old" and then you call it on person John from above, here is what happens:
st = showPerson john
-- gets expanded into:
showPerson (PersonConstructor "John" 42)
Under the hood it is simply a tuple ("John", 42) , and according to the pattern match on the left side of the showPerson definition, we get name = "John" and age = 42 . Then these values get substituted in the function body, and we get a resulting string. But nowhere is type Person used! The typechecker guarantees that the first value in a tuple received by showPerson will have type String , while the second will have Int , so it is impossible to have a runtime error !
In a general case, if you have a data constructor <Cons> T1 T2 ... TN that belongs to some type MyType and then you call it to create a value as <Cons> x1 x2 ... xn , Haskell stores it as a tuple (x1,x2, ..., xn) of type MyType . The type is used during the typechecking stage and then gets erased, while type safety is guaranteed ( proved ) by math.
For sum types, the situation is a bit trickier. Recall our type of Shapes :
data Shapes = Point Double Double | Circle Double Double Double
area :: Shapes -> Double
area (Point _ _) = 0
area (Circle _ _ r) = pi * r * r
It has in this case two data constructors – Point and Circle , which behave exactly as described above. Function “area” during compilation gets rewritten using case analysis, in pseudocode:
area (s :: Shape) = case <constructor of s is> of
Point -> 0
Circle -> <get 3rd element of the (x,y,r) tuple and substitute for r in pi * r * r>
This means that for sum types of more than one data constructor, Haskell needs a way to distinguish between data constructors with which this or that tuple has been created. So, even though information that s is a Shapes type is erased, we keep the constructor number inside the type together with our tuple. So that Point 4 0 would be represented something like (0, 4, 0) (in reality it’s done differently – more efficiently – but this illustrates the concept well enough) where the first value of the tuple is the constructor tag. GHC uses a lot of very smart optimizations under the hood where this approach has minimal possible overhead at runtime as well.
List, Recursion on Types and Patterns
Let’s go back to our card dealing magic spells. To (almost) fully understand it, there’s only one extremely important piece missing: List type function and recursively defined types, which are extensively used in functional programming to implement various data structures. If you recall, in Chapter 1 we described List as some manipulation that takes all possible combinations of values of another type and creates a new type from it. Try to define the List type function yourself before reading further.
Here is how we can operationalize this definition:
data List a = Cell a (List a) | Nil
-- or, in GADT syntax:
data List a where
Nil :: List a
Cell :: a -> List a -> List a
Diagram illustrating a linked list structure. The first cell contains "Int 1" and "List *", pointing to the second cell with "Int 2" and "List *". This points to the third cell with "Int 2" and "List Nil", indicating the end of the list.
Figure 2-2
List structure
Remember how you need to read type definitions as type functions? In pseudocode – type function List (a : Type) = Cell (x:a, y: (List a)) + Nil() – List a is a type function from the variable a : Type that consists of two constructors: Nil , which is itself a value of type List a , and Cell , which takes a value of type a and a value of type List a ( this is where recursion comes into play! ) and returns another List a . Here Nil is the boundary case of our recursion, and Cell is a recursive function that constructs a list until it is terminated by the Nil value as the last element (see Figure 2-2 ).
LIST EXERCISE
Try constructing different lists, similar to how you “executed” the “fact n” function in the last chapter, from different types – make some lists of Ints, Strings, Chars, etc.
Let’s construct a list from values 1, 2, and 3. You have a constructor function Cell that takes two values – a value of some concrete type, in this case an Int , and a List of Int . What is the simplest value of type List ? Of course it’s a Nil ! So we can write Cell 3 Nil – and it will be a List Int ! Now, we can pass this list to another Cell call, like this: Cell 2 (Cell 3 Nil) – and we have yet another List Int . Apply it one more time, and you get Cell 1 (Cell 2 (Cell 3 Nil)) . Easy, right?
Basically, if you keep in mind that type functions and constructors are , well, functions, which follow all the same principles as “real” functions, this type building business should become very clear and easy for you.
TREE EXERCISE
Now, quick, grow a tree! Define a recursive tree type function – one that can create trees from any other types, similar to List.
We looked at the principle of how List a type function can be defined, but since in Haskell it is such a fundamental data structure, it is in fact defined with different constructor names and some syntactic sugar on top: Nil is in fact [] and Cell is defined as an operator : , so that our list of 1, 2, and 3 would be written as 1:2:3:[] or simply [1,2,3] – much more concise and convenient. You can write ["abc", "hello", "world"] , a value of type List String ; [1.0, 3.1415926, 2.71828] , List Double ; etc.
In the last chapter we introduced the type String as a set of all possible combinations of characters, or simply List Char . In fact, it is exactly how String is defined in Haskell – which is quite logical from the math point of view, but at the same time very inefficient in practice. It’s kind of the same as if we defined our numbers as 0 being an empty set, 1 being a set containing an empty set, and so on and then defined operations of addition and multiplication on top of it – instead of using CPU-supported ints, floats, and operations on them. It would work, and might look very beautiful mathematically, but would be thousand times slower than asking a CPU to compute 2 + 2 via native operations.
In a similar fashion, when you are writing real-world programs that do any noticeable amount of string manipulation, you should try to use the type Text instead of String . It is represented much more efficiently internally, fully supports Unicode, and will make performance generally better. With lists, the fastest operation is appending an element in the beginning of the list – x:list . Inserting something in the middle or in the end is a pain that grows proportionally to the length of the list (in computer science we write O(n) ).
To use Text , you should write
{-# LANGUAGE OverloadedStrings #-}
import Data.Text
s :: Text
s = "Hello World"
The first line here tells GHC to treat string literals as Text . Without it, you’d have to write a lot of annoying String-to-Text-and-back conversion statements. The second explicitly imports the Text data type for you.
Strings aside, lists are still very convenient for a lot of common tasks, as we will see down the line. Now that we know how to define functions and types, including recursive ones, we have a very powerful toolbox at our disposal already to start building something serious. Let’s practice by defining some useful functions.
Length of a List
Remember this from Chapter 1 ? Now that you know how a list is built, you can easily write it :
length :: [a] -> Int
length [] = 0
length (x:xs) = 1 + length xs
Here we use recursion (length calls itself) and pattern matching: if a length is applied to an empty list ( [] ), it returns 0 (boundary case for the recursion!), and if it is applied to a list, we return 1 plus length applied to the remainder of the list. (x:xs) is pattern-matching a specific constructor – x here is simply the first element of the list, and xs is the rest of the list. It might make more sense if we wrote it via Cell constructor: length (Cell x xs) = 1 + length xs . If you recall, Cell (or : ) takes two values – a value of type a and a List a – and creates a list from them. Here we are telling Haskell, If our “length” function receives a value that is constructed with the help of “:” constructor, take it apart into constituents and do something with them.
We have just defined our first polymorphic function – it works on lists of any type of values! We don’t care what kind of value is stored in our list, we only care about the list’s structure – you will see this as a recurring theme now and again, and this is another powerful aspect of typed functional programming. You define functions that work on types created from other “argument” types regardless of what these argument types are – you only care about the structure that the type function gives to a new type. Just like a “circle” is an abstraction of the sun, a vinyl record, and a coin, a type function is an abstraction of a lot of different potentially not very related entities. If you already started learning Haskell and got stuck on monad tutorials, this might be exactly the issue, being misled by false analogies. A circle is not the sun or a vinyl record, but it captures some common quality of both – they are round, even though at the same time the sun is hot and huge and a vinyl record can make you feel sad. The same with Monads – it’s merely an abstraction of some useful quality of very, very different types. You need to learn to see this abstraction, without being lost in and confused by analogies, recognize it as such, and it will all make sense.
Map a Function Over a List of Values
Do you recall a mapping example from the last chapter? Here’s how we can define the extremely useful map function :
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = (f x):(map f xs)
The type signature tells us that map takes a function that converts values of type a to values of type b , whatever they are, and a list of values of type a ( [a] ) and gives us a list of values of type b ( [b] ) by applying our function to all values of the first list. It is likewise defined recursively with the boundary case being an empty list []. When map gets a value that is constructed with the help of : from x of type a and xs – remainder of the list – of type [a] , we construct a new list by applying f to x and gluing it together with recursively calling map f over the remainder of the list.
Let us expand by hand what is going to happen if we call map (+2) [1,2] . (+2) is a function from Int to Int 1 – it takes any number and adds 2 to it. We want to apply it to all the elements of the list [1,2] – if you recall, internally it is represented as 1:2:[] . So
map (+2) (1:2:[])
-- pattern match chooses the case of (x:xs), with x = 1 and xs = 2:[]
((+2) 1) : (map (+2) (2:[]))
-- expanding recursive map call, we again pattern match the same case, expanding further:
((+2) 1) : ((+2) 2) : (map (+2) [])
-- expanding the last recursive map call, we match the "[]" now, and get the final result:
(+2) 1 : (+2) 2 : []
The end result of such a call is what’s called a thunk . In GHC, it will actually be stored this way until the actual values of the list will be required by some other function, e.g., showing it on the screen. Once you do that, GHC runtime will calculate all the sums and will produce the final list as [3,4] . This is part of Haskell being lazy and using the evaluation model “call by need.” More on it later.
Dwell on the expansion above a bit, and it should become very clear and easy to use. So much so that you can work on some more exercises.
FUNCTION EXERCISES
Define some more functions:
-
1.
“head” that returns the first element of the list.
-
2.
“tail” that returns the remainder of the list.
-
3.
“zipWith” that takes two lists of types “[a]” and “[b]” and a function f :: a -> b -> c that takes a value of type “a” and a value of type “b” and returns a value of type “c” and creates a new list of type “[c]” where each value is the result of applying “f” to corresponding elements of the first two lists. The type signature to help you a bit: zipWith :: [a] -> [b] -> (a -> b -> c) -> [c] .
-
4.
Write safe variants of all these functions using Maybe .
One other piece of Haskell goodies that is worth noting in our card dealing code:
fullDeck = [ Card x y | y <- [Clubs .. Hearts], x <- [Two .. Ace] ]
It is called a comprehension , which might be familiar to you from math, and it basically tells Haskell to build a list of Card x y from all possible combinations of x and y from the right side of |. [Clubs .. Hearts] creates a list of all values of type CardSuite starting with Clubs and until Hearts , the same for [Two .. Ace] for values of type CardValue . You can obviously use the same syntax for Int : [1 .. 100] would create a list of all values from 1 to 100. You can in fact use this syntax with all types that belong to so-called Enum typeclass – that’s what the deriving (Enum) statement is about, it makes sure we can convert values of our type to ints (details about typeclasses in the next chapters). Practice writing some comprehensions yourself, e.g., for pairs of int values, just pretend you want to put some dots on the screen and need to quickly create their coordinates in a list.
Info
You can also create infinite lists – try this in ghci REPL (might not work online): “[1 ..]”. It just keeps going forever, like the Energizer Bunny. Then, try this: “head [1 ..]” or “take 5 [1 ..]”. We just applied a function to an infinite list and it worked fine, because Haskell is lazy . Laziness is extremely useful and beneficial in a lot of real-world scenarios, in some of which it makes Haskell outperform C, but they are more subtle and we won’t be looking at them for quite some time yet, as well as what lazy and strict in fact mean.
Okay, so here’s the full text of the card dealing program, which you should now be able to fully comprehend :
import Data.List
import System.IO
-- simple algebraic data types for card values and suites
data CardValue = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace
deriving (Eq, Enum)
data CardSuite = Clubs | Spades | Diamonds | Hearts deriving (Eq, Enum)
-- our card type - merely combining CardValue and CardSuite
data Card = Card CardValue CardSuite deriving(Eq)
-- synonym for list of cards to store decks
type Deck = [Card]
instance Show CardValue where
show c = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] !! (fromEnum c)
-- please make sure to enable utf-8 in your terminal, otherwise you may get errors when trying to execute
instance Show CardSuite where
show Spades = "♠"
show Clubs = "♣"
show Diamonds = "♦"
show Hearts = "♥"
-- defining show function that is a little nicer then default
instance Show Card where
show (Card a b) = show a ++ show b
-- defining full deck of cards via comprehension; how cool is that?! :)
fullDeck :: Deck
fullDeck = [ Card x y | y <- [Clubs .. Hearts], x <- [Two .. Ace] ]
smallDeck = [Card Ace Spades, Card Two Clubs, Card Jack Hearts ]
main = print smallDeck >> putStrLn "Press Enter to deal the full deck" >> getLine >> mapM_ print fullDeck
We looked at how the card deck types are constructed in the beginning of the chapter in detail. Keyword data is used to define new types and new type functions, as we already learned. Keyword type defines a so-called type synonym . In this case we write type Deck = [Card] , and then we can use Deck everywhere instead of [Card] – so it’s mostly a convenience syntax for better readability, not so much useful here, but when down the line you will write State instead of StateT m Identity or some such, you’ll come to appreciate it.
Syntax instance <Typeclass> <Type name> where ... is used to make a type part of a certain typeclass . We will look at typeclasses in detail in the next chapters, but a basic typeclass is similar to an interface in Java (they can be much more powerful than Java interfaces, but that’s a future topic). A typeclass defines the type signatures and possibly default implementation of some functions, and then if you want to make a type part of a certain typeclass, you have to implement these functions for your type. Haskell also provides a powerful deriving mechanism, where a lot of typeclasses can be implemented automatically for your types. In the code above, we are deriving typeclasses Eq – which allows comparing values of our type – and Enum , which allows to convert values of our type to Int, and we hand-code typeclass Show for the types CardValue , CardSuite, and Card . We could have asked Haskell to derive Show as well, but then our cards wouldn’t look as pretty. Try it out – delete the instance Show... lines and add deriving (Show) to all types and run the program again!
A typeclass is another convenient and powerful mechanism to support abstraction and function polymorphism: without it, once you have defined a function show :: CardValue -> String , it would be strictly bound by its type signature. Then if you tried to define a function show :: CardSuite -> String , converting a different type to a string with a function of the same name, our typechecker would complain and not let you do that. Luckily, there’s a typeclass Show that defines a polymorphic (working on different types) function show :: a -> String , which lets us work around this limitation. A lot of the power of Haskell in the form of Monads, Arrows, Functors, Monoids, etc. is implemented with the help of typeclasses.
Further down, the fullDeck function creates a full 52-card deck with the help of a list comprehension, and smallDeck is just three random cards thrown together in a list.
Then, our main function follows an already familiar logic of break the problem down into smaller pieces and connect functions together making sure the types fit . We are showing smallDeck , waiting for a user to press “Enter,” and then mapping print over all elements of the fullDeck list to “deal” the full deck. mapM_ is almost like map that we already defined – it maps a function over the list elements. The difference is that print is not really a mathematical function with the likes of which we dealt with so far – it does not map a value of one type to a value of another type, it puts something on the screen via calling an operating system procedure that in turn manipulates GPU memory via a complex cascade of operations. That’s why mapM_ is constructed differently from map – even though its high-level purpose is the same. We call such kind of manipulation “side effects.” Side effects mess up our cute perfect mathematical world, but the real world is messy and all real-world programs are about side effects, so we must learn to deal with them!
As we shall very soon see, just like the sun, a vinyl record, and a coin are all round, Maybe a , List a , procedures with side effects, and a bunch of other very useful type functions have something in common as well – something that we will abstract away and that will make writing efficient and robust Haskell code for us an enjoyable and elegant endeavor.
Conclusion
In this chapter, we learned what algebraic data types are and how to construct them, how to build types from other types, how to define functions and data structures recursively, and how to start building polymorphic functions with the help of typeclasses . Now we can gradually move to more advanced Haskell topics, but before we do, let us look at a gentle Type Theory and Category Theory introduction to help structure what we’ve learned so far!
Footnotes
1
Strictly speaking, it is also a polymorphic function that works on any members of the Num typeclass, but we will get there.