This post covers recursion in Clojure. A recursive function is one that calls itself. Since every function call results in a stack frame being placed on the call stack, regular recursion runs the risk of 'blowing up the call stack' which is bad. Tail recursion, with recur
is an efficient way to simulate recursion without the downsides.
Tail recursion
These are examples of using recursion.
- Tail Recursion
- Recursion and Fizz-Buzz
- Recursion and Square Roots
- Converting a String to an Integer in the Bases 2-16
- Mortgage Scheduler
Call to Action
Problem 1
Write a recursive function to reverse the letters of a string.
(reverse-string "Mark Mahoney") ;;returns "yenohaM kraM"
You may need to create a recursive 'helper' function that takes a different number of parameters than the non-recursive function or use the loop
form. Make sure you use recursion with the recur
form so that you do not 'blow the stack'.
Problem 2
Write a function that will join a series of strings together separated by another string. The function should create and return a new string. Use recursion with recur
.
(defn join [separator & parts]
;;your code here)
(join ", " "Mark" "Laura" "Buddy" "Patrick" "Willy") ;;"Mark, Laura, Buddy, Patrick, Willy"
Problem 3
Write a function that takes in an integer and converts it to a string. The user can specify the base that the string is in from 2-10. The program should use recursion and recur (either a recursive function or the loop form).
Comments and Feedback
You can find all of these code playbacks in my free 'book', An Animated Introduction to Clojure. I am always looking for feedback so please feel free to comment here or to send me a message. You can follow me on twitter @markm208.
Top comments (0)