gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
write simple Clojure code example, please
- User
write simple Clojure code example, please
- Assistant
Certainly! Here’s a simple Clojure example that defines a function to calculate the factorial of a number. This example demonstrates basic Clojure syntax, function definition, and recursion.
(defn factorial [n] (if (<= n 1) 1 (* n (factorial (dec n))))) ;; Testing the factorial function (println "Factorial of 5:" (factorial 5)) (println "Factorial of 0:" (factorial 0))Explanation:
defn: This is used to define a new function.factorial: Name of the function.[n]: Function parameter.if: This is a conditional expression. Ifnis less than or equal to 1, it returns 1 (base case). Otherwise, it calculatesn * (factorial (dec n)).dec: A function that decrements its argument by 1.println: Used to print output to the console.
How to Run:
You can run this code in a Clojure REPL or any Clojure-friendly environment like ClojureScript, Leiningen, or just in an online Clojure REPL. When executed, it will print the factorial of 5 and 0.