Created
July 25, 2011 16:57
-
-
Save mikera/1104578 to your computer and use it in GitHub Desktop.
Clojure quick tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, very nice....