Happy Learn Haskell Tutorial Vol 1

Buy now at Leanpub

Please Buy now at Leanpub

Written and illustrated by GetContented.

Published on 2016-12-19.


Contents

Main Table of Contents
Previous chapter: 4. The Main Road
5. Function Magic
... 5.1. A Story of Magic Coins
... 5.2. After the Story
... 5.3. Functions that Return Functions
... 5.4. Homework
Next chapter: 6. Sockets & Plugs

5. Function Magic 🔗

One of the simplest types possible has only two values. They represent truth and falsehood. In Haskell, this type is called Bool (short for boolean), and its two values are named True and False:


True :: Bool
False :: Bool

In later chapters, we’ll see how important these two values are. We’ll use them for checking things, and doing all sorts of other useful things. For now, we’re going to use them to introduce you to how to really think about functions.

5.1. A Story of Magic Coins 🔗

Let’s imagine you’re a book-seller on holidays looking for a good spot to read a pocket book called “The magic language of Haskell”, and you end up in a milk bar on planet Boolean where the local currency is Bool coins. You just bought a milkshake, and now you really want to play your favourite song on the jukebox as you read, so you open up your money holder, and here’s what you see:

Drats! Mostly False coins. The jukebox takes two True coins, and you only have one of them.

You spy a misshapen robot character at one end of the bar who might be a Haskell wizard. Maybe this guy can help.

He puts down his milkshake, and as you explain your plight to him, he stops frowning and clicking his tongue and reaches into his cloak. Pushing a small glowing bag in your direction, he seems genuinely happy to be able to help.

“You pay for these by learning how they work” he says simply, refusing your offer of paying with False coins. Satisfied, you take the bag and look inside as you walk to the jukebox. You pick out one of the glowing coins inside, and take a look. It appears to be made of something magical:

You notice an inscription on the coin. It looks like some kind of arcane magical writing, obviously written in Haskell, the ancient magical language of the robot wizard folk:


(\x -> True) :: Bool -> Bool

You’re a little familiar with this language yourself. Being a book-seller, you like to read many of the titles you stock, some of them about Haskell. Happily you remember you just happen to have that beginner’s pocket guide to the Haskell language in your back pocket. Oh yes, that was why you came in here in the first place, to read it!

You recall that the arrow symbol (->) usually indicates a function: that is, a mapping from one type of things to another type. However, here there is a True value on the right, and \x on the left. These aren’t types. What’s going on?

You consult your pocket book, and after a few minutes of rifling through the pages, you discover that this is a thing called a lambda, in coin form. A lambda, you read, is a function with no name: a way of getting a completely new value from a value. It also says functions are values, too, but you don’t know what that could possibly mean, so you ignore that for now.

The syntax, (that is, the way it’s written), has \ followed by a variable name that represents what you are applying this function to. This variable can be used in the area to the right of (->). It seems this lambda isn’t using the (x) variable name it has at all. This lambda produces a new True whenever you apply it to any True or False value and ignores the x variable entirely.

This is great! It’s just what you wanted. You can take your False coins and make new True ones from them! Those wily robot wizards, making such magic!

You take one of your coins, and you place it to the right of the magic coin, so its magic will bind them together. POP!

The magic coin pops, they both disappear, and a brand new True coin appears! Slowly you realise you just did something very silly, though.

The coin you applied to the magic coin was that single True coin you already had! So it did nothing, effectively. You write this down in the margin of your book, for future reference:


(\x -> True) True -- Equals True
-- Pointless waste. Don't do this!

The -- code is called a comment, and it’s not part of the code, it’s just for marking notes you can write to readers of your code, including yourself. When Haskell sees --, it will ignore all the writing to the right of it until the end of the line.

You wrote parentheses around the lambda expression. If you didn’t, Haskell would think the first True was a function, and that you wanted to apply it to the second True, and that would cause Haskell to not compile your program.

So now you’ve used your single True coin, but you got another one in its place, so no harm done you suppose to yourself, though you did just use up one of your magic lambda coins.

Time to try with a False coin. Frrrrzzzzt... POP! Brilliant! It worked. You now have two True coins so you can play your song. You note your new discovery in your note-book:


(\x -> True) False -- Equals True

Before you play your song though, you get curious. What if you fed one of your magically created coins into another one of those magic coins? Will it explode? Will the world stop?

Furtively, you glance over toward the robot wizard for guidance, but he appears to be engaged in an apparently amusing conversation with himself about folding wizard gowns into luggage and catamorphisms, whatever they are.

Why not try! You quickly grab a magic coin, and thrust one of your newly made coins next to it. POP! again. It does exactly what happened the first time. So you write this down, too:


(\x -> True) ((\x -> True) False) -- equals True

You read that back and it looks a little complicated. The part on the right is the coin that resulted from shoving a False into the magic coin. Then we put that whole bracketed thing on the right of another magic coin. It’s correct, just has lots of things going on!

You slide over to the juke box, put your coins in and then begin listening to the sweet sounds of Never Gonna Give You Up by Rick Astley, a timeless classic on your home-world.

You go back to your seat and keep reading the book a bit more. You’ve seen definitions before. You know how to make them. We see a definition for a magic coin:


magicCoin :: Bool -> Bool
magicCoin = \x -> True

You read on and find out that because we’re not using x in the body of our function, we can actually replace it with the underscore character; “_” to say that this is a function that has one argument, but it won’t be used. Fascinating, you think, as you hum happily, sipping your shake.

5.2. After the Story 🔗

We leave our story here, but we see that we can use the magicCoin function in the same way that we used putStrLn earlier, except because magicCoin has type Bool -> Bool, we can feed an applied expression of it into another application of it.


magicCoin :: Bool -> Bool
magicCoin = \_ -> True

newCoin :: Bool
newCoin = magicCoin False

newCoinAgain :: Bool
newCoinAgain = magicCoin newCoin

newCoinAgain' :: Bool
newCoinAgain' = magicCoin (magicCoin False)

We can keep applying it as many times as we like, however this magicCoin function is only useful if you want to take a True or False and make a sure it's a True.

There’s another way to write this function in Haskell. Let’s take a look at it:


magicCoin' :: Bool -> Bool
magicCoin' _ = True

We don’t have lambda syntax here. This is regular function definition syntax. We’re using “_” to pattern-match on any value at all, and not use it.

We could have also written this function like this, listing out one equality definition for each value in the argument:


magicCoin'' :: Bool -> Bool
magicCoin'' True  = True
magicCoin'' False = True

There is no reason to do this with our trivial example, but this shows you another way to write functions. We could write a function that flips a boolean value to its opposite value. This is actually built into Haskell already as the function named not, but we’ll make our own, and show you how easy it is to read it:


not' :: Bool -> Bool
not' True = False
not' False = True

This means we first check if the input value is True, and if so, we return False. If it's False, we return True. This is called pattern matching. It's just simple pattern-matching: matching on the values.

5.3. Functions that Return Functions 🔗

Let’s look at another lambda, but this one will return the magicCoin function! Let’s really think about this. Functions are values just like Bool values or String values or any other type of values. What about the type of this function that returns a function? It will take a Bool, and return a (Bool -> Bool), that is, it returns a function from Bool to Bool, so this is what we’re looking at:


(\_ -> magicCoin) :: Bool -> (Bool -> Bool)

Let’s set this up as a definition. We’ll call it magicBool:


magicBool :: Bool -> (Bool -> Bool)
magicBool = \_ -> magicCoin

Those types don’t need brackets, because they naturally group up to the right. This is a function that takes two arguments! Let’s remove the brackets from the signature, and spell magicCoin out as a lambda.


magicBool' :: Bool -> Bool -> Bool
magicBool' = \_ -> (\_ -> True)

We’ve included parentheses for you to understand better, but they’re not needed here. There are actually two other ways we could write this, let’s see:


-- using two lambdas,
-- without parentheses
magicBool'1 :: Bool -> Bool -> Bool
magicBool'1 = \_ -> \_ -> True

-- using just one lambda
magicBool'2 :: Bool -> Bool -> Bool
magicBool'2 = \_ _ -> True

So, how would we use this? Well, It’s a function so we can just give it any Bool value, then it’ll give us back the magicCoin function as a value! Then, if we want to, we can give that another Bool value, and it’ll give us back the value True.

This might seem useless at first, but let’s switch it into normal function syntax, and then we’ll look at a very useful function.


magicBool'' :: Bool -> Bool -> Bool
magicBool'' _ _ = True

Ok, so what if we wanted a function that tells us if any one of two values is True? This is a function that is built into Haskell, you’ll see it later. If you’re this high, or you’re an adult, you can ride the scary ride!

Here’s how it could be made with what we know so far:


eitherTrue :: Bool -> Bool -> Bool
eitherTrue False False = False
eitherTrue _     _     = True

So if both the arguments are False, we should reply with False, however for everything else, the answer is going to be True. (That is: either one is True, or both are True).

Neat, isn’t it? This is a very useful function, and programmers use it all the time.

This process of making a function that returns a function itself is called currying after the mathematician Haskell Curry (yes, that’s why Haskell is named Haskell). This is how Haskell takes arguments. By doing more, we can get more than 2.

What about something more involved, like maybe adding two Integer numbers? Well, we’ll show you this here just now, but it’s really the topic of the next section, so don’t worry if you don’t quite get it yet.

We’re going to define a function called plus that takes an Int value (Int is a whole number type), and returns a function that takes another Int value and returns the first added to the second. We’re going to use the (+) operator / function here. Just ignore it for now other than to know that it’s the way to add two numbers in Haskell.


plus :: Int -> Int -> Int
plus x y = x + y

plus' :: Int -> Int -> Int
plus' = \x -> \y -> x + y

increment :: Int -> Int
increment = plus 1

increment' :: Int -> Int
increment' = (\x -> \y -> x + y) 1

additionResult :: Int
additionResult = plus 100 25

First we have plus, which takes two arguments and returns the first added to the second (using the (+) operator).

Next we have plus' which does the exact same thing, but we’re using lambda syntax, and nesting one lambda in another.

Then increment, which uses the plus function and gives it one of its two arguments, which as we know will give us another function back. (Which will add one to whatever you give it). After that we have the same function done with lambdas: increment’. Finally, we have a definition for the expression of adding 100 to 25.

5.4. Homework 🔗

This chapter might have seemed pretty simple or quite easy for you, but what we just saw is very deep, so it’s worth thinking about some more.

Haskell functions cannot take multiple arguments, only one each. However, what they can do is return another function. The way we get functions to work with more than one argument in Haskell is to wrap other functions around them, as we saw above. In other words, to make functions that give functions as their result.

If each of these functions that are returned also take an argument, we can create a kind of chain of arguments. Let’s see.

When we see this:


add :: Int -> Int -> Int
add x y = x + y

It’s just a “sweeter”, easier, more convenient way of writing this:


add :: Int -> (Int -> Int)
add = \x -> (\y -> x + y)

We can put a number into x by applying the function to an argument, and we get a function back: add 2 for example:


add :: Int -> (Int -> Int)
add = \x -> (\y -> x + y)

-- substitute 2 in for x.
-- note that this is not Haskell code,
-- it's just to show you what happens:
-- add 2 is equal to \2 -> (\y -> 2 + y)
-- add 2 is equal to        \y -> 2 + y

If you wanted, you could call this a partial function application, but it’s really not what’s going on. All Haskell functions only take one argument, so all we’ve done is supply the add function (which produces another function) with one argument.

When we write add 2 3 what we’re actually doing is supplying a function-producing function with one argument (add 2) and then immediately providing the function that gets produced by that with the 3 argument: (add 2) 3.

Your homework is to read through this very well, and really try to understand it. Try out all of the program fragments in this chapter, and if you don’t understand any of this at all, write to us and tell us so we can adjust the book. All of the rest of your Haskell understanding relies on understanding this. We will explain it a little more in the next chapter, but it’s quite important.

If you’ve already learned another programming language, then this particular point will be incredibly difficult to understand for you. If you haven’t learned another programming language before, it’s going to be much easier because the way Haskell works is simpler, in the sense that it is not as complex. Of course if you’ve learned something complex and you think that is ordinary, when you see something simple it makes things very difficult to understand.

You’ll often hear us talking about things like “a function of two arguments” or, “put the letter 'x' in as the third argument”, but this is just an easier way to say what we mean. It’s not accurate, but we can use the short-hand form because we all understand that Haskell functions only take one argument, and when we say a function of two arguments, we really mean a function that produces a function that uses both their arguments in its inner body.


If you’ve enjoyed reading this, please consider purchasing a copy at Leanpub today

Please follow us, and check out our videos Follow @HappyLearnTutes

Also, Volume 2 is now in beta and being written! Show your support and register your interest at its Leanpub site.


Main Table of Contents
Previous chapter: 4. The Main Road
5. Function Magic
... 5.1. A Story of Magic Coins
... 5.2. After the Story
... 5.3. Functions that Return Functions
... 5.4. Homework
Next chapter: 6. Sockets & Plugs