📜  Clojure defn - Clojure (1)

📅  最后修改于: 2023-12-03 14:40:06.521000             🧑  作者: Mango

Clojure defn - Clojure

Clojure is a modern, functional programming language built on top of the Java Virtual Machine. It is designed to be a general-purpose language that is easy to read and write, and that provides a lot of power and flexibility to developers.

One of the most important features of Clojure is its support for functions. In Clojure, functions are first-class citizens, which means that they can be treated like any other value. This power and flexibility is provided by the defn function, which is used to define functions in Clojure.

Syntax

The basic syntax of defn is as follows:

(defn function-name
  [args...]
  body)
  • function-name: The name of the function
  • args: The arguments that the function takes (as a vector)
  • body: The body of the function

Here's an example:

(defn hello-world
  []
  (println "Hello, world!"))

In this example, we've defined a function called hello-world that takes no arguments and simply prints "Hello, world!" to the console.

Arguments

Clojure functions can take any number of arguments, and the arguments can be of any type. Here's an example that takes two arguments and returns their sum:

(defn add
  [a b]
  (+ a b))

In this example, we've defined a function called add that takes two arguments (a and b) and returns their sum.

Recursion

Clojure's support for recursion makes it a powerful choice for writing algorithms and other complex code. Here's an example of a recursive function that calculates the factorial of a number:

(defn factorial
  [n]
  (if (= n 0)
    1
    (* n (factorial (dec n)))))

In this example, we've defined a function called factorial that takes a single argument (n) and returns the factorial of that number. If n is 0, the function returns 1. Otherwise, it multiplies n by the factorial of n-1.

Conclusion

Clojure's defn function is a powerful tool for defining functions in Clojure. With support for recursion and first-class functions, Clojure provides a lot of power and flexibility to developers, making it a great choice for a wide range of projects.