If you’ve been programming for very long, you might’ve heard of the “fizzbuzz” problem. It was once a common interview question that was asked to see whether candidates could write a simple program, and it’s still used these days as a common example when teaching new programmers. There are a few minor variations of the problem, but let’s consider this version of it:
Given a number, fizzBuzzCount , return a string that contains all of the numbers from one, up to and including fizzBuzzCount , except:
-
If the number is evenly divisible by 3, but not evenly divisible by 5, replace it with the word “fizz”.
-
If the number is evenly divisible by 5, but not evenly divisible by 3, replace it with the word “buzz”.
-
If the number is evenly divisible by both 3 and 5, replace it with the word “fizzbuzz”.
For any given individual number, we can use what we’ve already learned in this chapter to write a function that will return the right output. Let’s start there by writing a new function, fizzBuzzFor , that will calculate the “fizzbuzz string” for any given number:
| | module FizzBuzz where |
| | |
| | fizzBuzzFor number |
| | | 0 == number `rem` 15 = "fizzbuzz" |
| | | 0 == number `rem` 5 = "buzz" |
| | | 0 == number `rem` 3 = "fizz" |
| | | otherwise = show number |
The rem function that we’re calling here returns the remainder after dividing two numbers. By checking to see if the remainder is zero, we can tell if one number is evenly divisible by another. You might also notice that our first case tests to see if our number is evenly divisible by 15. This is a shortcut that will tell us if the number is divisible by both 3 and 5.
This solves the problem for a particular number, but how can we go about calling this function repeatedly for each of the numbers up to our fizzBuzzCount ? Most idiomatic Haskell solutions to this particular problem would use lists and list functions that you’ll learn about in the next chapter . For now though, we’ll focus on the fundamentals.
In procedural and object-oriented languages, the common approach to solving a problem like this would be to use a loop , for example, a while or for loop. Let’s look at an example of how we might write this in a procedural way. This example will use JavaScript, but don’t worry if you aren’t familiar with JavaScript. We’re only using this example so that we have something concrete to reference when discussing the differences between procedural style looping and writing loops in Haskell.
| | function rem(a,b) { |
| | return a % b; |
| | } |
| | |
| | function fizzBuzzFor(number) { |
| | if (0 == rem(number, 15)) { |
| | return "fizzbuzz" ; |
| | } else if (0 == rem(number, 5)) { |
| | return "buzz" ; |
| | } else if (0 == rem(number, 3)) { |
| | return "fizz" ; |
| | } else { |
| | return number.toString(); |
| | } |
| | } |
| | |
| | function fizzbuzz(fizzBuzzCount) { |
| | var fizzBuzzString = "" ; |
| | for ( var curNum = 1; curNum <= fizzBuzzCount; curNum = curNum + 1) { |
| | fizzBuzzString = fizzBuzzString + " " + fizzBuzzFor(curNum); |
| | } |
| | return fizzBuzzString; |
| | } |
We’ll ignore the definition of rem here, which is included to keep our function names consistent with the Haskell code we’ve already written. We’ll also skip past fizzBuzFor , which is more or less identical to our earlier Haskell implementation, except for the obvious differences in syntax. Instead, let’s jump right to our definition of fizzbuzz .
The first thing we do in our fizzbuzz implementation is to declare some new mutable variable named fizzBuzzString . We initialize this variable to the empty string, and we accumulate the results of our loop into it. Our loop starts out by creating another mutable variable named curNum . At each iteration of the loop we first test to see if the current value of our mutable curNum counter is still within the bounds of our fizzBuzzCount . If it is, then we we modify our mutable fizzBuzzString value to append the current fizzbuzz value, and then we increment the counter. Eventually, when the counter is past the bounds of fizzBuzzCount the loop will exit and we’ll return the final value of fizzBuzzString .
Some of the words we just used to describe our procedural algorithm, like mutable and update , are clues that we might not be able to directly translate this looping approach to Haskell. After all, Haskell variables aren’t mutable, and in a pure function we have nothing to update. It’s true that we don’t want to directly translate the use of mutable values and state into Haskell, but an idiomatic Haskell implementation is still quite similar to this procedural one. Let’s look at a couple of ways that we can approach this sort of problem in Haskell.
The first thing we want to do when we’re thinking about writing a looping function in Haskell is to ask ourselves “what’s changing?” In our procedural implementation, we have three important pieces of state :
- fizzBuzzCount is immutable and tells us when to stop looping.
- fizzBuzzString is mutable, and accumulates the output of the function.
- curNum is the current number we’re fizzbuzzing. It’s also mutable and changes once per loop iteration.
Our pure functional fizzbuzz implementation will need the same state that the procedural one did. The key difference is that the state in our pure functional version will be immutable. When we had mutable state we needed to start our function by initializing the state, and we had to finish our function be extracting the final return value from our state. In the pure functional version, we’ll accept immutable state as input, so there’s nothing to initialize. That means our Haskell function will be equivalent to the body of our procedural loop—we don’t need to worry about the initial setup of the function, nor how to extract a final return value.
Let’s start our pure functional implementation by creating a new function. We’ll start with the most straightforward translation of our procedural algorithm, and refactor based on what we learn, so let’s call this first implementation naiveFizzBuzz :
| | module FizzBuzz where |
| | |
| | naiveFizzBuzz fizzBuzzCount curNum fizzBuzzString |
The first thing the body of our for loop did was check to see if our mutable curNum value was greater than the target fizzBuzzCount . If so, we would exit the loop and return the final string. Comparing two values and returning another value doesn’t require any mutation, so we can translate that step directly:
| | module FizzBuzz where |
| | |
| | naiveFizzBuzz fizzBuzzCount curNum fizzBuzzString = |
| | if curNum > fizzBuzzCount |
| | then fizzBuzzString |
| | else |
| | -- fill this in next |
In this expanded example, we’re looking to see if we’ve finished our loop, and if so we return fizzBuzzString . Just like in the procedural example, we’re making an assumption here that when we get to the end of our loop, the state of fizzBuzzString should be right, and we can return it. But how do we get the state there without changing it? In the body of our procedural loop, if we weren’t finished looping then we would change the state of the string by appending the next fizzbuzz number to it. Let’s add that to our Haskell example:
| | module FizzBuzz where |
| | |
| | naiveFizzBuzz fizzBuzzCount curNum fizzBuzzString = |
| | if curNum > fizzBuzzCount |
| | then fizzBuzzString |
| | else |
| | let nextFizzBuzzString = fizzBuzzString <> fizzBuzzFor curNum <> " " |
| | -- fill this in next |
Instead of modifying the string in place, our pure implementation will generate a new string. In this example, we’re calling that new string nextFizzBuzzString .
The next thing our procedural loop did was update the curNum counter by incrementing it. Just like with nextFizzBuzzString we’re going to create a new counter instead of modifying the one we have:
| | module FizzBuzz where |
| | |
| | naiveFizzBuzz fizzBuzzCount curNum fizzBuzzString = |
| | if curNum > fizzBuzzCount |
| | then fizzBuzzString |
| | else |
| | let nextFizzBuzzString = fizzBuzzString <> fizzBuzzFor curNum <> " " |
| | nextNumber = curNum + 1 |
| | in -- fill this in next |
The last thing that our procedural loop did was to, well, loop . After updating the mutable state, we would re-execute the same code in the body of the loop, and do the same things, but of course on the next run all of the values have been updated. The state of fizzBuzzString would have one more entry appended to it, and curNum would be one step closer to the end of our range of numbers.
In our pure functional version, we’re going to do the same thing. We’ll run the same code, but this time our curNum will be one step closer to the end, and fizzBuzzString will have one more entry added. How? By calling naiveFizzBuzz with the new values we’ve just calculated:
| | module FizzBuzz where |
| | |
| | naiveFizzBuzz fizzBuzzCount curNum fizzBuzzString = |
| | if curNum > fizzBuzzCount |
| | then fizzBuzzString |
| | else |
| | let nextFizzBuzzString = fizzBuzzString <> fizzBuzzFor curNum <> " " |
| | nextNumber = curNum + 1 |
| | in naiveFizzBuzz fizzBuzzCount nextNumber nextFizzBuzzString |
If you haven’t spent much time working with recursion, this can be a little bit confusing. Let’s work through what’s going on in this example to help make it a bit more clear. You can start by copying the code into a file and loading it into ghci so you can have an idea of what to expect:
| | λ :load FizzBuzz .hs |
| | [1 of 1] Compiling FizzBuzz ( FizzBuzz .hs, interpreted ) |
| | Ok , one module loaded. |
| | λ naive FizzBuzz 3 1 "" |
| | "1 2 fizz " |
When you need to understand what’s happening in a particular Haskell function, or even an entire program, one incredibly useful feature of Haskell is referential transparency . This is a fancy sounding term, but it basically means since everything in a Haskell program is a pure value, we can always replace a variable with its value, and any function call with the value that it returns, and the program shouldn’t behave any differently. Let’s take advantage of this and replace the variables we’re using to hold our state with their actual values in our function. This will represent the very first iteration of our loop:
| | naiveFizzBuzz 3 1 "" = |
| | if 1 > 3 |
| | then "" |
| | else |
| | let nextFizzBuzzString = "" <> fizzBuzzFor 1 <> " " |
| | nextNumber = 1 + 1 |
| | in naiveFizzBuzz 3 nextNumber nextFizzBuzzString |
Now that we’ve replaced the inputs with their values, let’s do some simplification. First, we can remove our if expression since we know that 1 > 3 will never be true. While we’re at it, we can replace our call to fizzBuzzFor 1 with the actual value, and combine all of the string fragments. We can also simplify the addition that we’re using to calculate nextNumber . When we do all that, we’ll end up with:
| | naiveFizzBuzz 3 1 "" = |
| | let nextFizzBuzzString = "1 " |
| | nextNumber = 2 |
| | in naiveFizzBuzz 3 nextNumber nextFizzBuzzString |
Finally, let’s make one more set of substitutions, and replace nextNumber and nextFizzBuzzString with their values:
| | naiveFizzBuzz 3 1 "" = |
| | naiveFizzBuzz 3 2 "1 " |
Now that we’ve simplified out all of the intermediate steps, we can see that when we call naiveFizzBuzz with one state, it simply calls itself with the next state. This is analogous to how our procedural loop runs with a new state each time it evaluates the loop body.
Recursion can be tricky to follow, so let’s take advantage of referential transparency and expand our call again. We can replace the call to naiveFizzBuzz with its definition, just like we replaced variables with their values:
| | naiveFizzBuzz 3 1 "" = |
| | if 2 > 3 |
| | then "1 " |
| | else |
| | let nextFizzBuzzString = "1 " <> fizzBuzzFor 2 <> " " |
| | nextNumber = 2 + 1 |
| | in naiveFizzBuzz 3 nextNumber nextFizzBuzzString |
Again, let’s simplify things by removing our if expression and simplifying our nextFizzBuzzString and nextNumber expressions:
| | naiveFizzBuzz 3 1 "" = |
| | let nextFizzBuzzString = "1 2 " |
| | nextNumber = 3 |
| | in naiveFizzBuzz 3 nextNumber nextFizzBuzzString |
After simplifying our expressions, we’re again left with a recursive call, but this time our state is one step closer to our final goal. Expanding naiveFizzBuzz and simplifying once more, we’ll have:
| | naiveFizzBuzz 3 1 "" = |
| | if 3 > 3 |
| | then "1 2 " |
| | else |
| | let nextFizzBuzzString = "1 2 fizz " |
| | nextNumber = 4 |
| | in naiveFizzBuzz 3 nextNumber nextFizzBuzzString |
Again we can remove our conditional, since 3 > 3 will always be false, and replace our variables with their values in our call to naiveFizzBuzz to get a simple recursive call:
| | naiveFizzBuzz 3 1 "" = |
| | naiveFizzBuzz 3 4 "1 2 fizz " |
This last call will be a little different. When we expand it this time the first branch in our if expression will be True :
| | naiveFizzBuzz 3 1 "" = |
| | if 4 > 3 |
| | then "1 2 fizz " |
| | else |
| | let nextFizzBuzzString = "1 2 fizz " <> fizzBuzzFor 4 <> " " |
| | nextNumber = 4 + 1 |
| | in naiveFizzBuzz 3 nextNumber nextFizzBuzzString |
When we simplify this time, we’ll drop the second part of our if expression, and we’re left with:
| | naiveFizzBuzz 3 1 "" = "1 2 fizz " |
We never evaluate the second branch of our conditional, so we do not make another recursive call. The branch we did evaluate simply returns the input string that we’ve been accumulating. When we’re writing recursive functions, we call the condition that causes the recursion to end the base case .
If you haven’t spent much time with recursion, it is worth reading this section a few times. Internalizing how to think about problems recursively can take a little bit of time and is often a matter of looking at many examples, so if you are still finding it hard to fully understand this example you can continue reading and you’ll have several more opportunities to work through similar problems over the next few chapters. The important thing to note here is that while we never introduced any mutable state, by using recursion we were able to implement the same kind of logic, and solve the same kinds of problems that you might use for and while loops for in a procedural language.