Skip to content

Instantly share code, notes, and snippets.

@ctford
Last active February 4, 2016 15:19
Show Gist options
  • Save ctford/5d21465b46641c70fdd6 to your computer and use it in GitHub Desktop.
Save ctford/5d21465b46641c70fdd6 to your computer and use it in GitHub Desktop.
Clojure introduction
; Why Clojure?
;
; * Interactive
; * Succinct
; * Consistent
; * Java interoperability
; Try Clojure is an online "repl", where you can try out Clojure expressions.
; http://tryclj.com/
; Simple values are echoed back from the repl.
1
;> 1
[1 2 3]
;> [1 2 3]
; Wrapping an expression in ()s causes a function to be invoked.
(+ 1 2)
;> 3
; The function is always comes in first position.
(- 2 1)
;> 1
(* 3 4)
;> 12
(* 3 (+ 2 2))
;> 12
; Exercise - try out some arithmetical expressions.
; Exercise - what does (doc +) do?
; We can define our own values.
(def age 99)
;> #'sandbox15110/age
age
;> 99
; Exercise - define pi.
; We can define our own functions.
(def plus-one (def [x] (+ x 1))
;> #'sandbox15110/plus-one
plus-one
;> #'sandbox15110/plus-one
(plus-one 2)
;> 3
; Exercise - define your own minus-one function.
; Exercise - define your own area function.
; Exercise - extract square into its own function.
; We can write out lists.
[1 2 3]
;> [1 2 3]
; There are library functions that work on lists.
(first [1 2 3])
;> 1
(take 2 [1 2 3])
;> [1 2]
(drop 1 [1 2 3])
;> [2 3]
; Exercise - define an xth function that returns the xth element of a list.
; (xth 0 [1 2 3]) should return the same as (first [1 2 3])
;
; Hint: you can write it in terms of first and drop.
; Some functions return boolean values.
(= 3 4)
;> false
(< 2 3)
;> true
; We can use if to branch.
(if (= 4 5) "goodbye" "hello")
;> "hello"
(if (> 3 2) "goodbye" "hello")
;> "goodbye"
; Exercise - write a maximum function, the greater of its two arguments.
; Exercise - write an absolute function, that returns 3 if given 3, and 4 if given -4.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment