Defining functions in Haskell may look strange, because of how lightweight the syntax is compared to other languages. In fact, the syntax for defining functions and variables in Haskell looks almost identical.
To define a new named function, give the function a name along with names for each of the parameters that you want to accept. To look at a concrete example, let’s rewrite our greeting program from earlier so that we can take a variable greeting and person to greet.
We’ll start by creating a new function, makeGreeting , that takes two arguments, salutation and person . We’ll use the <> operator to concatenate the two strings and add a space between them. The return value of the function is the concatenated string. Create a new Main.hs and copy the following example to get started.
| | module Main where |
| | |
| | makeGreeting salutation person = |
| | salutation <> " " <> person |
| | |
| | main = print "no salutation to show yet" |
Now load up ghci and test out your new function by calling makeGreeting "Hello" "George" .
You might notice that we’re not doing anything special to return a value from our function. Later in this book you’ll learn how to be explicit about the return value of your function. For now though, you can rely on knowing that the value of the expression in your function is the return value of the function.
You can also create anonymous functions using a backslash ( \ ) followed by the parameters for the function, and then an arrow (->) followed by the body. For example, you could create an anonymous version of the makeGreeting function with:
| | \ salutation person -> salutation <> " " <> person |
In addition to the term “anonymous function,” you’ll sometimes see these unnamed functions referred to as “lambda functions,” “lambda abstractions,” or simply “lambdas.” All of these names refer to the same concept. In this book we’ll use “anonymous function” consistently.
Functions close over the values that are in scope when they are defined, meaning that the variables that were in scope when you defined the function are also in scope inside of the function. That means you can also nest anonymous functions. All of the functions in the next example will behave the same way:
| | makeThruple a b c = (a,b,c) |
| | lambdaThruple a b = \ c -> (a,b,c) |
| | lambdaThruple' = \ a -> \ b -> \ c -> (a,b,c) |
In fact, in Haskell all functions only take a single argument. Functions that appear to take multiple arguments, like makeThruple and lambdaThruple are really just shorthand for a function like lambdaThruple’ that creates a new function for each parameter. The process of converting a function that takes multiple arguments into a series of single-argument functions is called currying . Although many languages support some form of currying, Haskell is somewhat unusual in the fact that all functions are curried by default. As you’ll see later in this section, and throughout this chapter, automatic currying makes some common Haskell idioms much easier to use.
You’ve already called functions several times as you’ve worked through this chapter, from functions like print to main . So far, every time you’ve called a function you’ve given it all the arguments that it expects. When a function is called with all of its arguments and can return a value that isn’t a function, we call it fully saturated . It’s also possible, and common, to call a function with only some of its arguments. We say these functions are partially applied .
makeGreeting :
| | greetPerson = makeGreeting "Hello" |
| | λ greetPerson "George" |
| | "Hello George" |
| | λ greetPerson "Jane" |
| | "Hello Jane" |
In this example, you created a new function called greetPerson by giving makeGreeting its first argument, but not the second. This pattern of partial application also works when you’re defining new functions. Say you wanted to make a new function that makes greetings more enthusiastic by adding an exclamation point to the salutation, but otherwise you wanted to re-use the logic from makeGreeting . You can do that by writing a function that partially applies a modified salutation to makeGreeting . Let’s see an example:
| | enthusiasticGreeting salutation = |
| | makeGreeting (salutation <> "!" ) |
You could also add an extra parameter to enthusiasticGreeting just to pass it along to makeGreeting :
| | enthusiasticGreeting salutation name = |
| | makeGreeting (salutation <> "!" ) name |
In fact, the process of adding or removing those extra parameters has a name that you’ll sometimes see used in Haskell. Removing the extra parameter, as in the first example, is called eta reduction or η -reduction . Adding a parameter and passing it along is called eta expansion . It’s useful to know these terms because you’ll run into them occasionally in the Haskell community, and may see them used in the output of some tools like code linters. For now it’s enough to know that η -reduction is generally idiomatic in Haskell.
Operators, like (*) and (<>) , are just functions that are infix by default. You can partially apply them like any other function, except that you need to put parentheses around the expression. In fact, you can partially apply the left or right-hand operand independently. Try running these examples in ghci to get a feel for how you can use partial application:
| | λ half = (/2) |
| | λ twoOver = (2/) |
| | λ half 10 |
| | λ half 20 |
| | λ twoOver 2 |
| | λ twoOver 8 |
You can also turn regular functions into infix functions by surrounding the function name with backticks. This can sometimes help make code more readable in general, and is especially handy when you want to partially apply the second argument of a function. Here are some examples. Try typing them into ghci .
| | λ greetGeorge = (`makeGreeting` "George" ) |
| | λ greetGeorge "Hello" |
| | λ greetGeorge "Good Evening" |
The flip function is another handy way to apply only the second argument of a function. You could write flip yourself easily:
| | flip someFunction arg1 arg2 = someFunction arg2 arg1 |
You can use flip in the same place that you’d backticks:
| | λ greetGeorge = flip makeGreeting "George" |
| | λ greetGeorge "Good Afternoon" |
| | "Good Afternoon George" |
You might notice that when you write flip makeGreeting "George" that makeGreeting is applied to flip first, and then "George" is passed in to the resulting function. That is because of the precedence of function application. In Haskell, function application has a high precedence, and it associates left to right, so flip makeGreeting "George" is the same as writing (flip makeGreeting) "George" . Sometimes the precedence of function application will require you to use parentheses. For example, imagine a function that combines three strings:
| | λ sayThree a b c = a <> " " <> b <> " " <> c |
If you call flip on this, as you’ve done in the earlier examples, you’ll flip the first and second arguments:
| | λ flip sayThree "Good" "Afternoon" "George" |
| | "Afternoon Good George" |
If you want to flip the second and final arguments, you need to use parentheses to partially apply the first argument to the function first:
| | λ flip (sayThree "Good" ) "Afternoon" "George" |
| | "Good George Afternoon" |
Composing Functions
Now that you understand more about creating and calling functions in Haskell, it’s time to learn about function composition. Fundamentally, function composition is about building functions that bring together two or more smaller functions into a single larger function. In this general sense, using function composition to build abstractions is what all programming is about.
Let’s look at an example of some code we might write without function composition. We’ll start by defining a few new functions that will do some basic arithmetic on a number. You can write these in ghci or follow along with the example by creating Chapter1.hs and adding them there.
| | module Chapter1 where |
| | |
| | addOne num = num + 1 |
| | timesTwo num = num * 2 |
| | squared num = num * num |
| | minusFive num = num - 5 |
Now that we’ve defined some functions that we want to use, let’s load them into ghci and use them to generate a final value:
| | λ :load Chapter1 .hs |
| | [1 of 1] Compiling Chapter1 ( Chapter1 .hs, interpreted ) |
| | Ok , one module loaded. |
| | λ result1 = add One 1 |
| | λ result2 = timesTwo result1 |
| | λ result3 = squared result2 |
| | λ minusFive result3 |
| | 11 |
In this example, we’re composing all of our functions by creating intermediate values and passing them around. This works, but it’s tedious and error prone since we might accidentally pass in the wrong intermediate variable, and if we want to edit code like this later we could end up having to rename several intermediate variables. Instead, we can use parentheses to call one function directly with the output of another function. This makes it much easier for us to re-use a particular collection of functions that are being called in a certain way. For example, let’s add a findResult function to Chapter1.hs that will compose the functions this way:
| | module Chapter1 where |
| | |
| | addOne num = num + 1 |
| | timesTwo num = num * 2 |
| | squared num = num * num |
| | minusFive num = num - 5 |
| | |
| | findResult num = minusFive (squared (timesTwo (addOne num))) |
Let’s see this in action by loading the file up in ghci again. If you haven’t closed your ghci session already, you can use the :reload command to load the newest version of Chapter1.hs . For a single file, this won’t make much difference, but :reload can be substantially faster when you are editing large projects.
| | λ :reload |
| | [1 of 1] Compiling Chapter1 ( Chapter1 .hs, interpreted ) |
| | Ok , one module loaded. |
| | λ find Result 1 |
| | 11 |
| | λ findResult 7 |
| | 251 |
As you can see, our new version of the function is not only easier to read, it’s also easier to call with different values.
Since composition is something we do so frequently in Haskell programs, there are a couple of tools we have at our disposal to make this even easier: two functions named ($) and (.) . The function application operator , ($) , helps us avoid having too many parentheses when we write code. The function composition operator , (.) , helps us quickly build new functions by combining existing ones.
Let’s start by looking at an example of how we can use ($) to help us write easier-to-read code. As you’ve seen, Haskell’s normal function application syntax is extremely lightweight. We just add the names of arguments right after the name of the function.
| | λ addOne 1 |
As you work through this book, you’ll learn about several advantages to this syntax, but it has a significant drawback: if we want to use the output of a function call as the input of a second call, the obvious way to write that would have some ambiguity. Look at this example:
| | λ addOne timesTwo 1 |
| | |
| | <interactive>:36:1: error: |
| | • Non type-variable argument in the constraint: Num (a -> a) |
| | (Use FlexibleContexts to permit this) |
| | • When checking the inferred type |
| | it :: forall {a}. (Num a, Num (a -> a)) => a |
As the authors of this code, we might know that our intent is to pass the result of timesTwo 1 into addOne , but Haskell will interpret this as though we are trying to pass two arguments to addOne , the first argument being the function timesTwo and the second argument the number 1 . Haskell is a functional programming language that makes heavy use of passing around first class functions, so this is an entirely sensible thing we might want to do sometimes, but for now it just means we’ll get an error message. Don’t worry about the specific meaning of the error text here. You’ll learn more about how to read error messages later, when you start to learn more about working with types .
One way that we can fix this error is by adding parentheses:
| | λ addOne (timesTwo 1) |
In small examples like this, parentheses are a helpful way to ensure that the code is evaluated the way you intend. In other cases, parentheses may not be very readable, and in those situations you can use the function application operator ($) , which applies the function on the left-hand side to the value on the right-hand side. The trick is that this operator has very low precedence, so the right-hand side will be evaluated before the function is applied to it. This has the same effect as wrapping everything after the ($) in parentheses. So you could rewrite the earlier example this way:
| | λ addOne $ timesTwo 1 |
The choice of when to use ($) is largely stylistic. We’ll use it in this book when it enhances readability, and skip it when it makes the code less readable.
Next, let’s look at the function composition operator, (.) . This operator is a higher-order function , a term you’ll hear used from time to time to describe functions that accept another function as an argument, or return a function. The (.) operator does both. It combines two functions and gives you a new function that accepts an argument to the right-hand function, and passes that function’s output on as input to the left-hand function. It’s a simple function that you could easily write yourself:
| | (.) func1 func2 = \ arg -> func1 (func2 arg) |
You use (.) like any other operator, except its operands are functions. Let’s see an example:
| | λ timesTwoPlusOne = timesTwo . addOne |
The timesTwoPlusOne function returns a new function that will double a value after incrementing it. Notice that although timesTwoPlusOne is a function, you don’t have to specify any parameters for it directly. When you combine timesTwo and addOne with (.) , the result is a new function that takes a parameter. You can also chain multiple functions with (.) :
| | λ timesEight = timesTwo . timesTwo . timesTwo |
| | λ timesEight 3 |
| | 24 |
Let’s look at a few more examples:
| | λ doubleIncremented = addOne . addOne |
| | λ doubleIncremented 4 |
| | 6 |
| | |
| | λ (timesTwo . addOne . squared . minusFive) 128 |
| | 30260 |
It’s common to want to use (.) without making a named function. If you try to call a function that you’ve composed you might run into the same problem that you saw earlier when trying to manually compose functions:
| | λ timesTwo . timesTwo 3 |
| | |
| | <interactive>:34:1: error: |
| | • Non type-variable argument in the constraint: Num (a -> c) |
| | (Use FlexibleContexts to permit this) |
| | • When checking the inferred type |
| | it :: forall {c} {a}. (Num c, Num (a -> c)) => a -> c |
You can ignore the specifc text of the error message for now. The reason that you are getting the error is that calling timesTwo 3 is higher precedence than composing timesTwo . timesTwo . To create a composed function you need to use parentheses, or you can use the function application operator you learned about earlier in this section:
| | λ (timesTwo . timesTwo . timesTwo) 3 |
| | 24 |
| | λ timesTwo . timesTwo . timesTwo $ 2 |
| | 16 |
Using function composition to build more complex functions from smaller functions is one of the most common things that you’ll do while writing Haskell programs.
Writing Functions with No Named Parameters
Pointfree programming, sometimes called tacit programming , takes the ideas of η -reduction and function composition to their logical conclusion by writing functions that take no named parameters at all. For example, consider our original makeGreeting function:
| | makeGreeting salutation person = salutation <> " " <> person |
We can apply η -reduction once to remove the final named parameter quite easily:
| | λ makeGreeting' salutation = ((salutation <> " " ) <>) |
To take it a step further and write a pointfree version of the function requires that we rethink the structure of our function definition a little bit. Let’s re-write makeGreeting’ while retaining salutation first:
| | λ makeGreeting' salutation = (<>) (salutation <> " " ) |
This version of the function makes the second call to (<>) into a prefix function. Its first argument is the first half of our string, which combines salutation with a trailing whitespace. The second argument to the function, which we aren’t binding to a variable name here, is the string that will become the last half of the combined greeting.
As a next step, let’s replace the named salutation parameter with an anonymous function defined where we are using it:
| | λ makeGreeting' = (<>) . ( \ salutation -> salutation <> " " ) |
| | λ makeGreeting' "hello" "george" |
| | "hello george" |
This is getting closer to a completely pointfree program: we’re no longer binding any variables in our top level function declaration, but you might already see that we can easily drop the explicitly bound variable name inside of our anonymous function as well. We know that we could refactor this inner expression. For example, imagine if we broke this up into two separate functions:
| | λ firstPart salutation = salutation <> " " |
| | λ makeGreeting' = (<>) . firstPart |
| | λ makeGreeting' "hello" "george" |
| | "hello george" |
You could refactor firstPart to be pointfree by rewriting it:
| | λ firstPart = (<> " " ) |
| | λ makeGreeting' = (<>) . firstPart |
| | λ makeGreeting' "hello" "george" |
| | "hello george" |
Now you can substitute the definition of firstPart back into the definition of makeGreeting’ , leaving you with a fully pointfree definition:
| | λ makeGreeting' = (<>) . (<> " " ) |
| | λ makeGreeting' "hello" "george" |
| | "hello george" |
Pointfree functions in Haskell can sometimes make code much cleaner and easier to read, and can offer a more principled way of writing functions, or they can also greatly reduce the readability and maintainability of code. The threshold for whether to make a function pointfree or not is a matter of debate in the Haskell community. In this book we will use a mixture of pointfree and pointful functions. Try writing functions in both styles and figure out which approach you prefer.