6. Functions - Koans Walkthrough

This video covers functions. Clojure has amazing support for first-class functions, and among the most concise syntax for anonymous functions of any language.

Here is the 06_functions.clj source code:

(defn multiply-by-ten [n]
  (* 10 n))

(defn square [n] (* n n))

(meditations
  "Functions are often defined before they are used"
  (= __ (multiply-by-ten 2))

  "But they can also be defined inline"
  (= __ ((fn [n] (* __ n)) 2))

  "Or using even shorter syntax"
  (= __ (#(* 15 %) __))

  "Short anonymous functions may take multiple arguments"
  (= __ (#(+ %1 %2 %3) 4 5 6))

  "One function can beget another"
  (= __ ((fn []
           ((fn [a b] (__ a b))
            4 5))))

  "Higher-order functions take function arguments"
  (= 25 (___
         (fn [n] (* n n))))

  "But they are often better written using the names of functions"
  (= 25 (___ square)))

Clojure Koans Walkthrough in Light Table IDE

This screencast tutorial helps you learn the Clojure programming language. Experience the joy of Clojure in the Light Table IDE as we tour through the Clojure Koans, taking you all the way from Beginner to Intermediate to Advanced.

Clojure is a Lisp created by Rich Hickey that runs on the JVM, as an alternative to Java. ClojureScript can target the web browser environment, and node.js, by compiling down to JavaScript, using the Google Closure compiler. Clojure features immutability, functional programming, and being a Lisp, macros.