Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions clojure.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,59 @@ keymap ; => {:a 1, :b 2, :c 3}
(conj [4 5 6] input 8 9 10)) ;=> or in the middle !
; Result: [4 5 6 4 8 9 10]

; Destructuring
;;;;;;;;;;;;;;;

(let [[x y & more] [1 2 3 4]
{:keys [a b] :or {b 99}} {:a 42}]
[x y more a b])
; => [1 2 (3 4) 42 99]

; Loops
;;;;;;;;;;;;;;;

(loop [n 10 acc 0]
(if (zero? n)
acc
(recur (dec n) (+ acc n))))
; => 55

(for [x (range 5) :when (even? x)] (* x x))
; => (0 4 16)

; Does not retain the head of the sequence. Returns nil.
(doseq [x (range 3)]
(println "side effect" x))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might deserve an explanation

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vendethiel thanks, done.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That looks like an explanation from the docs, but I thing the more important part is that it does all side effects

; "side effect 0"
; "side effect 1"
; "side effect 2"
; => nil

; Exception Handling
;;;;;;;;;;;;;;;

(try
(/ 1 0)
(catch ArithmeticException e
:division-by-zero)
(finally
(println "always runs")))
; prints "always runs" -> returns :division-by-zero

; Records, Protocols, Multimethods
;;;;;;;;;;;;;;;

(defprotocol Greeter (greet [this]))

(defrecord Person [name]
Greeter
(greet [_] (str "Hi " name)))

(greet (->Person "Ada")) ; => "Hi Ada"

(defmulti area :shape)
(defmethod area :circle [{:keys [r]}] (* Math/PI r r))
(area {:shape :circle :r 3}) ; => 28.27…

; Modules
;;;;;;;;;;;;;;;
Expand Down