Title here
Summary here
Functions are central in Clojure. We’ll learn about functions with a few different examples.
(ns functions-example
(:require [clojure.core :refer [println]]))
;; Here's a function that takes two numbers and returns
;; their sum.
(defn plus [a b]
(+ a b))
;; In Clojure, functions can take multiple arguments without
;; explicitly declaring their types.
(defn plus-plus [a b c]
(+ a b c))
(defn -main []
;; Call a function just as you'd expect, with
;; (function-name args).
(let [res (plus 1 2)]
(println "1+2 =" res))
(let [res (plus-plus 1 2 3)]
(println "1+2+3 =" res)))
To run the program, you can use the Clojure CLI or REPL:
$ clj -M functions_example.clj
1+2 = 3
1+2+3 = 6
Let’s break down the key points:
defn
macro.(function-name arg1 arg2 ...)
.let
special form.Clojure’s functional nature allows for concise and expressive function definitions. The language emphasizes immutability and encourages a functional programming style.
There are several other features to Clojure functions. One is multiple return values, which we’ll look at next.