Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Clojure quick tutorial
;; Objective
;; 1. Learn Clojure by doing Clojure
;; Pre-requisites
;; You need to have a running Clojure REPL
;; see:
; Hello World in Clojure
(println "Hello World")
; Declaring a variable
(def x 1)
; Arithmetic
(+ 2 5)
; Arithmetic using already-defined variables
(+ x 10)
; Arithmetic with multiple parameters
(* 2 3 4 5)
; Defining a function
(defn add-two [num]
(+ 2 num))
; Applying a function
; note: in Lisp, the function you are applying goes first in the parentheses
(add-two 10)
; Defining a vector
(def numbers [1 2 3 4 5])
; Getting a value from a vector by index
; note: you can treat a vector as if it is a "function" mapping an index to values
(numbers 2)
; Getting the first few values from a collection
(take 3 numbers)
; reversing a sequence
(reverse numbers)
; Applying a function to all values in a collection
; Note that "map" is a "higher order function" since it takes a function as its first parameter
(map add-two numbers)
; Applying a function of two parameters function to all values in two collection
(map * numbers numbers)
; Applying an anonymous function to all values in a collection
(map #(+ % 100) numbers)
; Function that generates a function
; Note this is a "higher order function"
(defn make-adder [n]
(fn [x]
(+ x n)))
; Applying a generated function
((make-adder 7) 10)

cloxure commented Mar 6, 2014

nice, very nice....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment