public
Last active

Clojure quick tutorial

  • Download Gist
gistfile1.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
;; Objective
;; 1. Learn Clojure by doing Clojure
;;
;; Pre-requisites
;; You need to have a running Clojure REPL
;; see: http://clojure.org/getting_started
 
; 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)

nice, very nice....

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.