- Clojure - Libraries
- Clojure - Automated Testing
- Clojure - Applications
- Clojure - Concurrent Programming
- Clojure - Java Interface
- Clojure - Databases
- Clojure - Reference Values
- Clojure - Macros
- Clojure - Watchers
- Clojure - Agents
- Clojure - StructMaps
- Clojure - Metadata
- Clojure - Atoms
- Clojure - Date & Time
- Clojure - Destructuring
- Clojure - Predicates
- Clojure - Regular Expressions
- Clojure - Sequences
- Clojure - Exception Handling
- Clojure - Namespaces
- Clojure - Maps
- Clojure - Vectors
- Clojure - Sets
- Clojure - Lists
- Clojure - Strings
- Clojure - File I/O
- Clojure - Recursion
- Clojure - Numbers
- Clojure - Functions
- Clojure - Decision Making
- Clojure - Loops
- Clojure - Operators
- Clojure - Variables
- Clojure - Data Types
- Clojure - REPL
- Clojure - Basic Syntax
- Clojure - Environment
- Clojure - Overview
- Clojure - Home
Clojure Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Clojure - Recursion
We have seen the recur statement in an earper topic and whereas the ‘for’ loop is somewhat pke a loop, recur is a real loop in Clojure.
If you have a programming background, you may have heard of tail recursion, which is a major feature of functional languages. This recur special form is the one that implements tail recursion. As the word “tail recursion” indicates, recur must be called in the tail position. In other words, recur must be the last thing to be evaluated.
The simplest example of the recur statement is used within the ‘for’ loop. In the following example, the recur statement is used to change the value of the variable ‘i’ and feed the value of the variable back to the loop expression.
Example
(ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (loop [i 0] (when (< i 5) (println i) (recur (inc i))))) (Example)
Output
The above program produces the following output.
0 1 2 3 4Advertisements