Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

write simple Clojure code example, please

  1. User

    write simple Clojure code example, please

  2. 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:

    1. defn: This is used to define a new function.
    2. factorial: Name of the function.
    3. [n]: Function parameter.
    4. if: This is a conditional expression. If n is less than or equal to 1, it returns 1 (base case). Otherwise, it calculates n * (factorial (dec n)).
    5. dec: A function that decrements its argument by 1.
    6. 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.