Defining Pure Functions
Introduction to Pure Functions
Welcome back! In our previous units, you learned how to write your first Haskell program using main and explored core data types like Int and Double. Now that you know how to represent basic values, it is time to build your own tools to work with them. In this lesson, we will learn how to write our own custom functions.
In Haskell, we write what are called pure functions. You can think of a pure function as a simple vending machine. If you put in a specific code for a snack, you will always get the exact same snack. A pure function works the same way: if you give it the same inputs, it will always give you the same output. There are no hidden surprises, no unexpected changes to other parts of your program, and no side effects. This makes Haskell code very predictable and easy to trust.
Writing Single-Argument Functions
Before a function can perform calculations, we have to tell Haskell what type of data the function uses. We do this using a type signature. A type signature acts as a blueprint.
Let's create a simple function called double that takes a whole number and multiplies it by two. First, we write the type signature using an arrow (->):
In this signature, double is the name of our function. The :: symbol means "has the type of." The arrow (->) separates the input from the output. The last type in the line is always the output. Everything before it is an input. So, Int -> Int means this function takes one integer as an input and returns one integer as an output.
Next, we write the actual logic on the very next line:
Here, double n means our function takes a value and calls it n. The equals sign (=) starts the definition. Finally, n * 2 is the math that produces our output.
Because a single file can hold many different functions, let's add a second tool. We will create a square function that multiplies a number by itself.
Notice that square has the exact same type signature shape (Int -> Int) as double. This shows us that the type signature defines the shape of the data, but the internal mathematical logic is completely up to you!
Writing Multi-Argument Functions
