Category: Functions

  • Recursion: Start with the Base Case

    Recursion: Start with the Base Case

    Thanks to Eric Grimson for this idea. When you’re writing a recursive function… Write the base case first. That’s where it returns a value, instead of recursing. To show this, let’s write a factorial function. A factorial is a “product of all positive integers less than or equal to n,” according to Wikipedia. The factorial…

  • Loop in Clojure

    Loop in Clojure

    Here’s a way to avoid recursive helper functions… By using loop in Clojure. Sometimes recursive helper functions seem needed, like fibonacci-iter: (I ported this to Clojure from Structure and Interpretation of Computer Programs, licensed CC BY-SA-4.0) That fibonacci-iter helper function is only needed for recursion. For example, the public (defn fibonacci [n] only needs an…