Lesson 8. Writing recursive functions

 

After reading lesson 8, you’ll be able to

  • See common patterns of applying rules of recursion
  • Understand how to use recursion on lists
  • Learn to time functions in GHCi
  • Reason about the edge cases of our five rules of recursion

The best way to get better at recursion is to practice, practice, practice! In this lesson, we’ll walk through a variety of recursive functions to help you apply the rules of recursion presented in the preceding lesson. As you do this, you’ll start to see that a few patterns repeat when solving recursive problems. Because Haskell doesn’t allow you to “cheat” by using stateful iteration, nearly all the code you write in Haskell will involve some recursion (though often this is abstracted away). This will lead you to quickly becoming comfortable writing recursive functions and solving problems in a recursive style.

Consider this

In the preceding lesson, you were asked to consider writing a take function on your own. This time, consider the drop function:

drop 3 [1,2,3,4]
[4]

Write your own version of drop and consider how this function is both similar to and different from take.

8.1. Review: Rules of recursion

In the preceding lesson, you learned about the rules for writing recursive functions. Here they are again for easy reference:

8.2. Recursion on lists

8.3. Pathological recursion: Ackerman function and the Collatz conjecture

Summary

sitemap