© 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_1
1. Wizards, Types, and Functions
Anton Antich 1
(1)
Schaffhausen, Schaffhausen, Switzerland
You wake up in a cheap motel room in Brooklyn. You hear police sirens outside, the ceiling is gray and dirty, and a big cockroach is slowly crawling across. You don’t remember much, except that you need to be in a fancy restaurant in Manhattan at 7 PM – oh my, it’s in 15 minutes! – and that you are a wizard. The problem is, you only remember three spells (Figure 1-1 ).
A cartoon sequence showing three transformations. First, an angry bug labeled "K'hee-bah" transforms into a pig. Second, the same bug labeled "Moz'bah'da" transforms into a smiling horse. Third, a pig labeled "Gimmeraree" transforms into a red sports car.
Figure 1-1
The spells you remember
You are obviously in a hurry, so, looking attentively at a cockroach, you wave your hands and go: “Moz’bah’da!” And puff! There is a beautiful white horse right beside the bed! In a short moment, you realize that riding a horse through New York might not get you there on time, plus you are not sure you even can ride a horse, so you wave your hands again and shout: “Gimmeraree !”
The horse disappears in a puff of smoke, and all you get is a pile of stinking goo on the floor. Oh-oh. You forgot that “Gimmeraree” works only on pigs! Poor horse. You catch another cockroach, go outside, and this time say your spells in the correct order – “K’hee-bah!”, “Gimmeraree!” – and there you go, a red Ferrari Spider, in mint condition standing right there beside the garbage bins. Hastily, you jump into the car and drive away to a meeting that will hopefully clear up your past, present, and future destiny (see Figure 1-2 ).
In this book, we will study modern typed functional programming concepts and learn to apply them using Haskell, the most powerful and popular modern functional language. If you have previous imperative programming language exposure (C, C++, C#, Java, JavaScript, etc.), you might be anxious to jump right into writing your first “Hello World” program – we will get there soon enough. For now, I strongly encourage you to put away your imperative baggage, take a step back, and meditate a bit on how we approach solving problems the functional way. Trust me, it will be worth it in the long run: if you learn the concepts, which are much more powerful and elegant, but very different from the imperative world, you will become efficient much quicker – and then you can gradually add your imperative experience into the mix. For now, it is best to pretend it simply does not exist.
Typed functional programming is just like magic. Your spells are functions. They turn something into something else (like pigs to Ferraris or strings to numbers) or produce some effect (like putting ogres to sleep or drawing a circle on the screen), and you need to combine different spells in the right order to get to the desired result .
What happened in the story above was dynamically typed magic: you used a spell that works only on pigs on a horse instead, and your “program” crashed, killing the horse in the process (that’s what often happens with JavaScript programs). With the statically typed magic that we will use from now on, a powerful being called Typechecker would see your mistake, stop your hand, and tell you that “Gimmeraree” expects a pig as its input – which would indeed make you a much more powerful and successful mage than if you go around killing other people’s horses.
Solving Problems As Wizards Do
So how do we approach solving problems the functional way? The mage above needed to get a fast mode of transportation, and all he had were cockroaches. So he had to think about how he could get from a cockroach to a Ferrari using the spells he knows by combining them in the correct order. He started with an end result – Ferrari – and worked backward from there, getting to the correct sequence by composing spells that work on the right subjects.
An illustration showing a sequence with three elements. On the left, a cartoon cockroach labeled "K'hee-bah" points to a pig in the center. The pig is followed by an arrow labeled "Gimmeraree" pointing to a red sports car on the right.
Figure 1-2
Composing spells in the right order, minding the types
Now, let’s get real and say you need to calculate an average of a list of numbers and show it on the screen. Please resist the imperative urge to start telling the computer what to do and how to do it, and let’s focus on the problem as a wizard would instead.
You have a human, and you need to turn her into a line on the screen, hopefully without killing anyone. Let’s work backward from our desired result – “a line on the screen with the average printed out” (Figure 1-3 ).
Illustration showing a girl's face on the left with an arrow pointing to a question mark in the center. Another arrow points from the question mark to a dark textured square on the right, which contains the text "average: 5.23" in green.
Figure 1-3
Our first problem
To get to this result, we need something that takes a number and shows it on the screen. Let’s call this something “print” (Figure 1-4 ).
A cartoon girl with pigtails looks confused, indicated by a large red thought bubble with a question mark. An arrow points from the bubble to a smaller bubble labeled "number," leading to the word "print." Another arrow points to a dark rectangle with the text "average: 5.23" in green.
Figure 1-4
Step 1 in resolving the problem
Now our problem is a bit easier – we need to get from a human to a number. “Print,” whatever it is, needs a number to operate. Since our goal is to calculate and show an average value, the previous step needs to take a list of numbers and, uhm, calculate their average (Figure 1-5 ).
A cartoon illustration shows a person with a questioning expression, followed by a thought bubble labeled "list of num." This leads to another bubble labeled "calculate average," which points to "print." The final output is displayed as "average: 5.23." The image visually represents the process of calculating and printing the average of a list of numbers.
Figure 1-5
Step 2 in resolving the problem
Our problem became easier still – now we just need to extract the list of numbers from our human, and the solution is ready (Figure 1-6 )!
A flowchart illustrating a process with a cartoon face on the left. The steps include: "ask for a list of numbers," followed by "calculate average," then "print." An arrow labeled "list of num" connects the first two steps, and another labeled "number" connects to "print." The final output is shown as "average: 5.23" on a textured background.
Figure 1-6
Step 3 in resolving the problem
What did we just do? We have broken down or decomposed our problem into smaller pieces, solutions to which we already know or can come up with easily enough, and combined them in the right order to get to the desired result. Just like with the mage above, we cannot give a string or a horse to our calculate average – it expects a list of numbers , so it will not compose with functions that produce something other than a list of numbers! Thus, we came up not only with “spells” – functions that we would need to solve our problem – but also with types that our functions should work with: a list of numbers, a number, an effect of putting something on screen. From the start, just by thinking about how to solve a problem, we “invented” two most important concepts in programming, computer science, and mathematics itself: functions and types .
We’ll start looking at them more closely later in this chapter. For now, here’s a bit of real magic: as it turns out, Haskell code maps virtually one to one to this approach! Look at the first line of code below (don’t mind the rest for now):
main = ask >> getLine >>= toList >>= calcAverage >>= printResult
where calcAverage l = pure $ (fromIntegral $ sum l) / (lengthF l)
printResult n = putStrLn $ "Average of your list is: " ++ (show n)
ask = putStrLn "Enter list of numbers, e.g. [1,3,4,5]:"
lengthF = fromIntegral . length
toList :: String -> IO [Int] = pure . read
The first line is our sequence of “spells,” or, really, functions, that start with a human sitting at the keyboard and get us to the line on the screen with calculated average shown. First, we ask a human to enter the list of numbers with ask and pass whatever was entered to the next function – toList – to convert the string she enters to an actual List . The resulting list is given to the calcAverage function that in turn passes its result to printResult . Exactly what we came up with, reasoning about the problem in the passage above.
We started with the desired end result, worked backward by decomposing the big problem into smaller pieces, and connected or composed them so that the output type of one function fits to the input types of the next. This is the essence of every functional program. Lines of code after where further detail how the “spells” we are chaining should behave – don’t concern yourself with them yet. What’s important is to get a feel of the process:
-
What is our desired result?
-
What is our input?
-
Work backward from the result to the input, decomposing the problem into smaller pieces that we know how to solve, by thinking about how to convert between types along the way.
-
Compose smaller functions, each of which solves a smaller problem piece, together into a bigger function, making sure the types fit.
Question: Why are we working backward from the desired result instead of forward from the input? For elementary tasks, such as the one above or turning a cockroach into a Ferrari, it doesn’t really matter. When you start encountering more complicated real-world problems, it will be much easier to start with the type of the desired result – just like it is easier to solve a maze starting from an exit!
Practice this approach on some other problems you would like to solve. We will use it on quite a bit of the real-world problems further along.
Let’s Fall in Love with Types!
To become a powerful Haskell mage, you need to get to know and understand types intimately: their birth, their daily lives, and their relations with each other. Types come before functions and functions are meaningless without types. So what are types? Intuitively, a type is just a bunch of objects (or subjects) sharing some common characteristic(s) thrown in a pot together. You could say that the type of your Ferrari Spider is Car , as is the type of that Toyota Prius. The type of both a pig and a horse is Animal . The type of 1, 114, 27428 is Natural Number . The type of the letters “a,” “C,” “e,” “z” is Char (that’s an actual type for characters in Haskell). The last two are ubiquitous in programming, so let’s look at them more closely.
Let’s not forget that we are creative wizards, so we will be building a whole new world from scratch. We will call this world category “ Hask ” (for reasons that will become apparent much later), or simply Hask from now on, and it will be inhabited by types ; their members, or values ; functions ; and some other interesting characters. As we create this world, we will gradually become more and more powerful and eventually will be able to write efficient, elegant, and robust Haskell programs for any practical task.
A Char and an Int Walk into a Bar and Make a Function
Natural numbers are the most intuitive math concept that everyone is familiar with – that is what you use when counting the times you read confusing monad tutorial articles . Natural numbers start with nothing, zero, and go on forever. Once you subtract the number of times you read confusing monad tutorials (at least 37) from the number of times it made sense (0), you realize the need for negative numbers, which together with naturals give you another infinite type – integers. Various “ints” that you might be used to from the C-land, as well as the type Int in Haskell, are the teeny-tiny subset of real integers, limited by 2^31^-1 or 2^63^-1 on the 64-bit systems. What is 9,223,372,036,854,775,807 compared with infinity? Same as nothing, but, fortunately, it is enough for most practical purposes, including counting all the money in the world if you want to write a new automated banking system at some point.
Illustration comparing two data types: "Int" and "Char." The "Int" section, in blue, contains numbers 0 through 7, ending with an expression "(2^3-1)." The "Char" section, in orange, displays lowercase letters a to g, followed by uppercase letters X, Y, Z.
Figure 1-7
Introducing Int and Char types
Char is our second foundational type – a pot of all characters we use when writing stuff in different languages, including mathematics or Egyptian pictography if we want to get fancy. It is also a finite type and quite a bit smaller than Int at that .
By themselves, these types are quite boring (see Figure 1-7 ), and we can’t do much with them – it’s just lonely numbers and characters hanging out all by themselves. They are sort of like prisoners in solitary confinement with no way to interact with others. Let’s break them out and set them free to roam the world and talk to each other! To do this, we are going to need functions .
Note
What is called “functions” in the imperative world, be it JavaScript or C family, has very little in common with mathematical functions we are interested in. A JavaScript “function” better be called a “procedure” – as they used to be called in ancient times, before Facebook, when people still cared about being thorough, in languages such as Fortran. In a procedure, you tell a computer what to do – add some numbers, draw a circle, divide by zero – spaghetti of messy code thrown together. We want to be tidy, elegant, and comprehensible, so we will use real mathematical functions.
Let’s line up our characters from the Char type as they do in an English alphabet. Then we can ask each letter, “Which number are you?”, like in Figure 1-8 .
Diagram illustrating a mapping between integers and characters. On the left, a teal cloud labeled "Int" contains numbers 0 to 7, with a note "(2^3 - 1)" next to 7. On the right, an orange cloud labeled "Char" contains letters a to g, followed by ellipses, and ending with X, Y, Z. Arrows connect numbers 1, 2, 5, and 7 to letters a, b, e, and g, respectively, indicating a relationship or conversion between the two sets.
Figure 1-8
Introducing functions
We have just constructed our first function! What it does is match each letter with a number. Now, this is very important: it matches all letters with exactly one number. We could match just some letters to certain numbers – then our function would be called a partial function since it would be defined not for all members of our type. A function can map several members of a type to one member of another type, e.g., we could define a function that matches “a” and “b” to 1, “c” and “d” to 2, etc. – it would be a perfectly fine, even if a bit weird, function. However, what we cannot do is define a function that matches a member of a type to several members of another type (see Figure 1-9 ).
The image illustrates two diagrams comparing a "weird function" and "not a function." On the left, the "weird function" shows a set labeled "Int" with numbers 1, 2, 3, 4, 5, 6, 7, 0, mapping to a set labeled "Char" with letters a, b, c, d, e, f, g, X, Y, Z. Multiple numbers map to the same letter. On the right, "not a function" shows the same sets, but the number 2 maps to both 'a' and 'b', violating the definition of a function.
Figure 1-9
Functions and not functions
On the other hand, an imperative procedure , for instance, a JavaScript “function,” can take an “a” and return 1 on one day, “32” on another, or crash if the temperature in Alaska drops below zero. Our function , as any other real mathematical function, always gives you the same result for the same arguments, no matter what.
You can trust the word of a function. You cannot trust anything from a procedure .
Our function (let’s call it whichNumberIsChar ) takes a Char and gives an Int as a result. In Haskell, we write: whichNumberIsChar :: Char -> Int . You can try it live in your browser here https://repl.it/languages/haskell or by installing Haskell environment from Haskell.org and starting your REPL locally. Just type (cheating a bit since we are using another, much more powerful polymorphic Haskell function to define ours) let whichNumberIsChar = fromEnum :: Char -> Int . Then you can type whichNumberIsChar 'Z' (or some other character) and see what happens.
Our world is still very boring. We have two basic types living in it, and we have one function between them, but we can’t even add two numbers together! That’s not enough to solve a simple calculate an average for some numbers problem, let alone do something more interesting. However, it turns out that Int , Char , and some imagination can get us much further than may appear. Let’s make some more magic!
Diagram illustrating the concept of mapping integers to strings based on length. On the left, a teal shape labeled "Int" contains numbers 0 to 6 and a formula for the maximum value, 2^63-1. On the right, an orange shape labeled "String" contains text examples: 'abc', 'xyz', 'hello world', 'to be or not', and 'wizard'. Arrows connect numbers to strings, emphasizing the relationship based on string length. The word "length" is centered at the bottom.
Figure 1-10
More complex types and functions
How FunTypical!
First, we are going to need strings. What is a string? It’s basically just a bunch of characters put together in order. Like “abc,” “xyz,” or “Hello World.” This hints at how we can introduce the type String : it’s a set of all possible combinations of characters from Char . Easy, right? We can also introduce another obvious useful function right away, between String and Int , shown in Figure 1-10 , which gives us the length of a string: length :: String -> Int . Try it out in REPL by running ghci in your terminal, and you should see something like
GHCi, version 9.4.8: https://www.haskell.org/ghc/ :? for help
ghci> length "abc"
3
ghci> length "hello world"
11
ghci> :t length
length :: Foldable t => t a -> Int
Now, the last command – :t length – is interesting. As you can guess it prints out the type of any object in Haskell – extremely useful information. As you can see from the result, our length function has a type that is much more generic than what we have assumed – instead of String -> Int it has a type Foldable t => t a -> Int . We will learn what exactly this means soon enough. For now it suffices to know that it indeed works on strings.
How about “some numbers” type? We can use the same logic as above and introduce the type ListInt – a set of all possible combinations of numbers from Int , such as [1, 2, 3] or [10, 500, 42, –18]. What if we treat each string as a sentence and want to define a type Book that would contain a bunch of sentences together? Again, we can define it as a set 1 of all possible combinations of strings from String .
Do you notice a pattern? We take a type , apply some manipulation we describe as “ a set of all possible combinations ” to members of this type, and get a new type as a result . Doesn’t it look just like a function?! ( See Figure 1-11 . ) We just “turned” one type into a different type, just like the function length turns a string into an int.
The image illustrates different data types and their representations. In the top left, "Int" is shown with numbers like 1, 2, 3, and so on, up to 2^63-1. Below it, "ListInt" displays lists of integers such as [1, 2, 3] and [15, 18, -9, 7]. On the top right, "Char" includes characters like a, b, c, and X, Y, Z. Below it, "String" shows examples of strings such as 'abc', 'xyz', and 'hello'. Arrows labeled "List" connect "Int" to "ListInt" and "Char" to "String".
Figure 1-11
Constructing new types from existing types
Let’s call this manipulation List – just like in the picture. As we have defined functions whichNumberIsChar :: Char -> Int and length :: String -> Int , List is also indeed a function, one that takes a type and creates a different type ! In Haskell, we write List :: * -> * (* is a synonym for concrete Type in Haskell, so in fact this signature means List :: Type -> Type ). They are sometimes more formally called type-level functions , and they are the core of the beauty, elegance, and efficiency of Haskell. We will be doing a lot of type creating down the line!
Info
Now, since our String and ListInt were created in a very similar way, can we apply our length function to it? Try it out in REPL: length [1,2,3], length [], give it some other lists of numbers. Did it work?
Curry and Recurse!
We saw that a function takes one argument of one type and maps it to exactly one value of a different or the same type. A couple of questions should arise at this point :
-
What do we do with functions of several arguments that exist even in math – like f(x,y) = x + y – not just C-land programming languages?
-
How do we actually define functions without resorting to writing explicit tables that map arguments to results, something like “1 + 1 = 2, 0 + 1 = 1, 1 + 0 = 1 …” for all numbers? You could certainly do that, but it’s a bit unpractical, where by “unpractical” I mean totally nuts.
There are a couple of ways to tackle the first one. Let’s say we want a function that takes a Char and an Int , converts a character to a number with the help of our whichNumberIsChar function, and calculates the sum of the two, something like anotherWeirdFunction c i = (whichNumberIsChar c) + i – but we can’t do this since the functions we defined take only one argument! One way to work around it would be to somehow combine our Char and an Int into a new type of pairs ( Int, Char ) – similar to what we have done with List above – and write
anotherWeirdFunction :: (Char, Int) -> Int
anotherWeirdFunction (c, i) = (whichNumberIsChar c) + i
Now we are ok – our function takes just one argument. This is a perfectly valid way to do it, and we will see how to construct pairs from other types in the next chapter. However, it turns out it is much more powerful to use a different approach. First, one very important point:
Functions are first-class citizens in functional programming (that’s kind of why it’s called functional programming ) – which means you can pass a function to another function as an argument and return a different function as a result. This also means that we have types that are inhabited by functions – e.g., type of functions String -> Int would contain all possible functions that take a string and return an int value.
Let’s say you want to take a ListInt we defined above and multiply all its elements by some number n. In the imperative world, you would write a function that takes a list and a number n, goes through some cycle, and multiplies it. An okay approach, but what if later on you’d need to add a number n to all list elements? You’d need to write a different cycle that now adds numbers. Wouldn’t it be great if we could just pass a function that we want to apply to all list elements, whatever it is? In Haskell, you can, by simply writing
map (*2) [1,2,3]
\=> [2,4,6]
map (+2) [0,8,18]
\=> [2, 10, 20]
We pass a function that adds 2 – (+2) – or multiplies by 2, (*2) , and a ListInt to a function called map (we will define it in the next chapter) and get another list as a result. Much more concise and powerful than writing a lot of boilerplate imperative cycles and also hints at how we can define functions of multiple arguments by looking at some further examples:
-
(+) x y is a function of one argument that takes an Int and returns a new function that takes an Int and returns an Int. So (+2) is a function that adds 2 to any number, (+18) adds 18, etc. – and we create these functions on the fly by passing only one argument to (+) first. So the type signature of (+) is (+) :: Int -> Int -> Int , which you can read as (+) :: Int -> (Int -> Int) , i.e., exactly what we just wrote – it takes an Int and returns a function that converts Int to Int!
-
Our anotherWeirdFunction is defined similarly: it’s a function of one argument that takes a Char and returns a function of one argument that takes an Int and returns an Int:
anotherWeirdFunction :: Char -> Int -> Int
anotherWeirdFunction c i = (whichNumberIsChar c) + i
So, in general, a function of many arguments can be defined as a function that takes one argument and returns a function that takes one argument and returns a function … This technique is called currying , because that’s how you make chicken curry. No, not really. It was invented by Haskell Curry, in whose name both the currying and the Haskell language itself were named.
Currying is extremely useful, because it makes the math much simpler and allows you to create different functions on the fly and pass them around as you see fit.
Now, let’s turn to the second question – how to construct functions efficiently .
It is in fact possible to start with an empty set and define all of Haskell – first, you construct natural numbers starting with an empty set as we showed in an aside above; then you can define an operation of addition on these numbers, invent integers once you realize you need negative numbers, and then define multiplication via addition; etc. It is a long and winding road.
We won’t be doing that (although it’s a pretty cool exercise to do on your own) – since existing computer architectures provide a bunch of operations, such as addition, multiplication, and memory manipulation, for us much more efficiently than if we were to implement them from scratch by translating pure functional lambda calculus logic. Haskell additionally defines a bunch of so-called primops , or primitive operations , on top of those and then a bunch of useful functions in its standard library called Prelude – so you can obviously use all of them when writing your functions and do things like
square x = x * x
polynom2 x y = square x + 2 * y * x + y
Having said that, a very important concept in functional programming that we need to understand is recursion . It allows you to write concise code for some pretty complex concepts. Let’s start with the “Hello World” of functional programming – factorial function. Factorial of a natural number n is defined simply as a product of all numbers from 1 to n, and in Haskell you can simply write product [1..n] – but it’s too easy, so let’s create our factorial function recursively:
fact :: Int -> Int
fact n = if n == 0 then 1 else n * fact (n - 1)
What’s happening in recursion is that a function calls itself under certain conditions – in the case of fact , when n > 0. Try executing this function on a piece of paper with different arguments. For example, if we “call” fact 1 , here’s what’s going to happen:
[1] fact 1
[2] if 1 == 0 then 1 else 1 * fact (1 - 1)
[3] if False then 1 else 1 * fact 0
[4] 1 * fact 0
[5] 1 * (if 0 == 0 then 1 else 0 * fact (0 - 1))
[6] 1 * (if True then 1 else ...)
[7] 1 * 1
[8] 1
Phew. Now try expanding fact 10 on paper when you have half an hour to waste. There’s nothing complex about recursion – you (or a computer) simply substitute(s) a function call to the function’s body as normal, and the main thing to remember is that your recursion needs to terminate at some point. That’s why you need boundary cases, such as fact 0 = 1 in the case of factorial, but it can be completely different conditions in other functions.
EXERCISES
-
Our fact function as defined above has a problem. Can you find and fix it?
-
Define a multiplication function via addition recursively.
-
A very interesting case of recursion is the Ackermann function: https://www.wikiwand.com/en/Ackermann_function . Write it in Haskell but don't try calling it with more than ackermann 4 1 – even this case may take you some hours to compute. Practice expanding ackermann 1 1 on paper to understand internal recursion machinery.
Conclusion
In a very short time, starting with barely anything but an empty set, we have come up with the concepts of
-
Types, inhabited by their members, also called values . We have introduced two very simple types: Int and Char.
-
Functions, which map values of one type to values of another (or the same) type.
-
Type functions, which create new types from other types. We have introduced a couple of useful complex types: String and ListInt .
-
Composition, an essence of a functional program (and, incidentally, Category Theory, but we won’t be going there for quite some time yet).
-
Ways to construct functions via currying and recursion.
This is pretty much everything we need to gradually build our magical Hask world!
What is currently missing is details on how exactly we can define and use functions such as length that gives us the length of a String (or, as we have seen above, any other Type constructed with the help of our List type function!) and List that creates new types. We can’t just tell a computer, “Give me a set of all possible combinations” – we need to be slightly more specific.
In the next chapter, we will continue following the adventures of our mage and will focus on card magic while constructing different types and intimately understanding their internal structure – which is an absolute requirement for designing efficient functions.
Let’s roll up our sleeves and get to it!
Footnotes
1
Our manipulation procedure is not strictly creating “sets” in a mathematical sense of the word, since in a real set each object can only be present once. In our new “list” types, values may repeat – [1,1,1,1] is a perfectly valid list of ints in Haskell even though it’s not technically a set.