Please Buy now at Leanpub
Written and illustrated by GetContented.
Published on 2021-08-14.
One of the simplest possible types has only two values. They represent truth and falsehood. In Haskell, the values are
False, and the type is
True :: Bool False :: Bool
In later chapters, we’ll see how important these two values are. We’ll use them for checking what’s true, and doing all sorts of other useful things. For now, because they’re so simple — there’s just two of them after all — we’re going to use them to introduce how functions work in Haskell. We’ll use a story to explain them, but all the Haskell in the story is real, and not actually magic.
Let’s imagine you own a bookshop, space travel is common, and you’re on holidays on a foreign planet. You’re looking for a good spot to read a book you brought with you called “The magic language of Haskell”. The inhabitants of the planet you’re visiting, Planet Boolean, have a fondness for milkshakes so you end up at a milk bar. The local currency are
Bool coins and they’re described in Haskell, as above.
You just paid three
False coins for a yangmei milkshake, and now you really want to play your favourite song on the jukebox as you read. You look at your money container as you wander towards the jukebox:
False coins. it seems the jukebox takes two
True coins to play a song, and you only have one.
You spy a misshapen robot character at one end of the bar, muttering the word “lambda” over and over. Ordinarily you’d think it nothing more than a stressed-out robot, but the last chapter you read of your book described Haskell mage robots, and you recognise its robe. Maybe this robot can help you.
It puts down its milkshake as you explain your bother. After you finish, it pauses a moment then suddenly produces something from its cloak with a smile. It pushes the small, glowing bag in your direction, seeming very happy to be able to help.
“You pay for these by learning how they work” it says simply, refusing your offer of
False coins as payment.
Curious, you take the bag and look inside as you walk to the jukebox. You pick out one of the glowing coins from inside, and turn it over; it appears to be made of some quite mystical material you haven’t seen before:
You notice an inscription on the coin. You recognise its arcane magical writing; it’s written in Haskell, the ancient language of the robot mage folk:
(\x -> True) :: Bool -> Bool
You’re a little familiar with this language yourself. Happily, you remember you just happen to have that beginner’s guide to the Haskell language. Yes, that was why you came in here in the first place, to read it!
You recall that the arrow symbol
-> on types usually indicates a function: that is, a type mapping from one type to another type.
You already know that
Bool is the type of coins, which can be either
False. You also already know that
:: indicates that the value on its left is of the type to its right, as in
True :: Bool to say that the value
True has the type
You consult the book again and realise
(\x -> True) must be a value, and
Bool -> Bool must be its type. That means it must be a function from
Bool values to
Bool values! You also realise the left and right arrows
-> mean a different thing to each other, because they’re on different sides of
After a few minutes of rifling through the pages, you discover that
\x -> True is an example of a function literal, or another term for this is a lambda. A lambda, you read, is an inline function definition. The parentheses are only needed here to make sure
:: Bool -> Bool is referring to the whole lambda rather than just the
True on the right side of it.
So, this coin is a function! This is one way to define a function in Haskell (we’ll see many more in later chapters).
You realise that a function is a way of getting a completely new value from an existing value, sometimes using the existing value, sometimes not. It also says functions are values, too, so that means we can pass them into other functions, or return them from functions.
The syntax of a lambda, or the way it’s written, has a backslash (
\) followed by a variable name, (in this case
x). The variable name is standing in for whatever we apply this function to, when it gets applied. This variable can be used in the area to the right of
However, it seems our lambda coin isn’t using the
x variable name at all on the right hand side of
-> in the lambda. If it was written as
\x -> x then it would just give you back whatever value you put in, but
\x -> True will always produce a fresh
True value whenever you apply it to any
Bool value; it ignores its input argument, the
x variable, entirely. Functions are free to do this.
This is great, because it will do what you need. You can take your
False coins and make new
True ones from them! Those wily robot wizards are so clever, making such magic!
You take one of your coins, and you place it to the right of the magic coin, which will apply the function to the value, so the “magic” of function application will bind them together and produce a new value. POP!
The magic coin pops, they both disappear, and a brand new
True coin appears! Slowly, as you look at it, you realise you just did something very silly, though. This is what is written on it:
True -- from ((\x -> True) True)
Bool coin you applied to the
\x -> True lambda coin was that single
True coin you already had! So it did nothing, effectively, and you wasted a lambda coin. You write this down in the margin of your book, for the future:
-- Pointless waste. Don't do this! (\x -> True) True -- results in True
-- is called a code comment, and it’s not a meaningful part of the code for doing anything, it’s for writing notes or documentation 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 put parentheses around the lambda expression before you applied it to the coin. This is good, because if you didn’t, Haskell would think it meant a function that takes an argument and then tries to use the first
True as a function and apply it to the second
True like this:
\x -> True True, and that would cause Haskell to not compile your program, because it’s meaningless;
True isn't a function.
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.
Time to try with a
(\x -> True) False
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 created coins
((\x -> True) True) into another one of those lambda 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.
-- first we get a lambda coin: -- (\x -> True) -- then we get a fresh True coin we created from a lambda and a False: -- ((\x -> True) False) -- now we apply the lambda coin, by putting it on the left of the fresh True coin: (\x -> True) ((\x -> True) False)
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 really complicated. The part on the right is the coin that resulted from shoving a
False into the first lambda coin. Then we put that whole bracketed thing on the right of another lambda coin. It’s correct, it just has lots of things going on!
((\x -> True) False) actually gets turned into
True when it’s evaluated, and can never mean anything else, we could have just substituted
True instead, but that wouldn't explain the whole process.
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. The book has a definition for a magic coin:
lambdaCoin :: Bool -> Bool lambdaCoin = \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 that argument won’t be used. Fascinating, you think, as you happily sip your shake, humming along to the tune.
We leave our story here, but we see that we can use the
lambdaCoin function in the same way that we used
putStrLn earlier, except because
lambdaCoin has type
Bool -> Bool, that is, because both its argument and output types are
Bool, we can apply it as many times as we like, for example:
-- the function that always returns True no matter what Bool it gets lambdaCoin :: Bool -> Bool lambdaCoin = \_ -> True -- the value True, by applying the above lambdaCoin -- function to the value False newCoin :: Bool newCoin = lambdaCoin False -- the value True, by applying the above lambdaCoin -- function to newCoin which is itself arrived at by -- applying lambdaCoin to False newCoinAgain :: Bool newCoinAgain = lambdaCoin newCoin -- this is another way to write newCoinAgain, -- but explicitly spelling out -- all of the applications of lambdaCoin newCoinAgain' :: Bool newCoinAgain' = lambdaCoin (lambdaCoin False)
We can keep applying it as many times as we like. However, this particular function,
lambdaCoin, is not extremely useful. It’s only useful if you want to take any
Bool and get back a
There’s another way to write this function in Haskell. Let’s take a look at it:
lambdaCoin' :: Bool -> Bool lambdaCoin' _ = 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 say any value at all, but the type signature requires it to be a
Bool so it can actually only be one of
False. Don't get too worried or confused about this, we will go into more gradual detail on how to write functions in upcoming chapters.
We could have also written this function like this, listing out one equality definition for each value in the argument:
lambdaCoin'' :: Bool -> Bool lambdaCoin'' True = True lambdaCoin'' False = True
There is no reason to do this with our trivial example, but this shows you another way to write functions: we’re matching on each input value.
Another thing we could do is write a function that flips a boolean value to the other value. This is actually extremely useful, and built into Haskell already as the function named
not, but we’ll make our own, to show you how easy it is to write and 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. Instead, if it’s
False, we return
True. This is called pattern matching. It's just simple pattern-matching: matching on the values.
Let’s look at another lambda example. This one will actually return the
lambdaCoin function! We know functions are values, just like
Bool values or
String values or any other type of values. That means we can take them as arguments, and give them back as results of functions.
What is 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, so its type is
Bool -> (Bool -> Bool)
(\_ -> lambdaCoin) :: Bool -> (Bool -> Bool)
So we take any
Bool and return
lambdaCoin which is itself the function
\_ -> True. This is a function that takes two arguments!
Let’s set this up as a definition. We’ll call it
lambdaCoinTakesTwo :: Bool -> (Bool -> Bool) lambdaCoinTakesTwo = \_ -> lambdaCoin
The type actually doesn’t need parentheses on it, because they naturally group up that way. Let’s remove parentheses from the signature, and spell
lambdaCoin out as a lambda.
lambdaCoinTakesTwo' :: Bool -> Bool -> Bool lambdaCoinTakesTwo' = \_ -> (\_ -> True)
We’ve included parentheses for you to understand better, but they’re not needed in the lambda definition here either. There are actually a few other ways we could write this, let’s see two:
-- using two lambdas, -- without parentheses lambdaCoinTakesTwo'1 :: Bool -> Bool -> Bool lambdaCoinTakesTwo'1 = \_ -> \_ -> True -- using just one lambda lambdaCoinTakesTwo'2 :: Bool -> Bool -> Bool lambdaCoinTakesTwo'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
lambdaCoin function as a value! Then, if we want to, we can give that another
Bool value, and it’ll give us back the value
lambdaCoinTakesTwo False False -- will be True lambdaCoinTakesTwo True False -- will be True lambdaCoinTakesTwo False True -- will be True lambdaCoinTakesTwo True True -- will be True
This is a pretty pointless function. However, now we’ve seen how to use functions of two arguments, let’s switch the definition into normal function syntax, and then we’ll look at a very similar and actually very useful function:
-- a more normal way of defining the function lambdaCoinTakesTwo'' :: Bool -> Bool -> Bool lambdaCoinTakesTwo'' _ _ = True
What have we done here? This is another way to define the same function, only instead of writing it as a lambda, we’ve written it using function definition syntax. Don’t worry too much if this is confusing, we’ll introduce this more slowly and properly in the next chapters. For now, just know that it’s another way of defining the same function as
Ok, so what if we wanted a function of two boolean values that tells us if any one of the two values is True? For example, at a carnival, maybe the ride attendant wants to say “you can ride the scary ride, but only if you’re the right height, or you’re an adult”. Let’s write this logic in some Haskell:
tallEnough = False isAdult = False canRideScaryRide = False
Let’s say instead of just writing down the value for
canRideScaryRide directly, we want to have Haskell figure it out instead; and as we know, they can only ride it if they’re either tall enough, or they’re an adult, or both, so we want to base the value on
Here’s how we could define a function to help us do this:
isEitherTrue :: Bool -> Bool -> Bool isEitherTrue False False = False isEitherTrue _ _ = True
So this is another function definition. Here we’re making a new function called
isEitherTrue. We’re pattern matching on the arguments. In the first line, if both the arguments match as
False, the result will equal
False, and in the next line it says for every other combination of argument values (using the underscores to match anything), the result is going to be
True. (That is: when either one is
True, or both are
True). Again, if this is confusing, just make a note to come back and take a look after reading the next chapters.
Let’s see it in action:
tallEnough = False isAdult = False canRideScaryRide = isEitherTrue tallEnough isAdult -- this is False
Neat, isn’t it? This
isEitherTrue we’ve written is a very useful function, and programmers use it all the time, though the built in one is named differently. We’ll see that later.
Now we can change either of the dependant values, and know that
canRideScaryRide will get the right value without us having to do anything extra to its definition.
tallEnough = True isAdult = False canRideScaryRide = isEitherTrue tallEnough isAdult -- This will be True now
Because this is such a useful function, it’s actually already in Haskell as the logical or operator, and it works like this:
tallEnough = False isAdult = False canRideScaryRide = tallEnough || isAdult
There are other logical operators, too, and we’ll see them later.
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 using more functions, we can get more arguments. Of course, as we’ve seen, Haskell has a lot of nice syntax to make it easier to write functions of more than one argument because it’s such a common need.
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
Next we have
plus' which does the exact same thing, but we’re using lambda syntax, and nesting one lambda in another.
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.
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
(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.
Next, see if you can write a function similar to
isEitherTrue but that will only return
True when both are
True. Call this function
areBothTrue and try to use it to write a value for
canRideVeryScaryRide which is only for tall adults to ride. Try it out with different values for the two boolean values.
If you’ve already learned another programming language, then this particular point to do with currying will likely be fairly difficult for you to understand. 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 has less parts to it. Of course, if you’ve already learned a complex language 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 as you now know and understand, 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.