On Github bodil / workshop-clojure-slides
Before we start:
(println "Hello World!")
; strings "Hello sailor!" ; numbers 31337 ; symbols this-is-a-symbol ; keywords :this-is-a-keyword
(println "Hello World!") (1 2 3 "Hello" :world) (1 2 3 ("lists within lists"))
["This" :is "a vector" 1 2 3]
(defn hello-world [] (println "Hello World!")) (defn add-two [a b] (+ a b))
(defn number-as-text [number] (cond (= number 1) "One" (= number 2) "Two" :else "Many"))
(1 2 "fizz" 4 "buzz" "fizz" 7 ... 14 "fizzbuzz" 16 ...)
(defn number-as-text [number] (cond (= number 1) "One" (= number 2) "Two" :else "Many"))
Hint: (rem 7 3)
(with-test (defn fizz-buzz [x] (cond (= (rem x 15) 0) "FizzBuzz" (= (rem x 5) 0) "Buzz" (= (rem x 3) 0) "Fizz" :else x)) (is (= 1 (fizz-buzz 1))) (is (= "Fizz" (fizz-buzz 3))) (is (= "Buzz" (fizz-buzz 5))))
(fn [number] (+ number 2)) ((fn [number] (+ number 2)) 5) (def add-two (fn [number] (+ number 2)))
(map inc [1 2 3 4]) ; => [2 3 4 5] (map (fn [item] (+ item 2)) [1 2 3 4]) ; => [3 4 5 6]
(defn add-x [numbers x] (map (fn [number] (+ number x)) numbers)) (add-x [1 2 3 4] 5) ; => [6 7 8 9]
(filter pos? [-1 0 1 2]) ; => [1 2]
(defn greater-than [numbers x] (filter (fn [number] (> number x)) numbers)) (greater-than [1 2 3 4] 2) ; => [3 4]
(reduce + [1 2 3 4]) ; => 10 (reduce * [1 2 3 4]) ; => 24
(ones [1 1 4 5 6]) ; => 2 (twos [2 2 4 6 2]) ; => 6 (chance [2 2 4 5 4]) ; => 17
(defn greater-than [numbers x] (filter (fn [number] (> number x)) numbers)) (greater-than [1 2 3 4] 2) ; => (3 4)
Hint: Use reduce to add numbers
; a basic key/value store {:name "Mario", :occupation "Plumber"} {:name "Luigi", :occupation "Plumber"}
(def mario-map {:name "Mario", :occupation "Plumber"}) (mario-map :name) ; => "Mario" (assoc mario-map :name "Wario") ; => {:name "Wario", :occupation "Plumber"}
(frequencies ["Mario" "Mario" "Luigi" "Mario"]) ; => {"Mario" 3, "Luigi" 1} (frequencies [5 4 3 4 6]) ; => {3 1, 4 2, 5 1, 6 1}
(def names ["Mario" "Luigi" "Bowser"]) ; look up an index on a vector (names 1) ; => "Luigi" ; length of a vector (count names) ; => 3
(defn greater-than [numbers x] (filter (fn [number] (> number x)) numbers)) (frequencies ["Mario" "Mario" "Luigi" "Mario"]) ; => {"Mario" 3, "Luigi" 1}
(def board [[:b nil nil] [nil nil nil] [nil nil :b]]) (with-test (defn mines ... (is (= 2 (mines board [1 1]) (is (= 0 (mines board [0 2]))) (is (= 1 (mines board [1 2]))))
(def board [[:b nil nil] [nil nil nil] [nil nil :b]]) (with-test (defn mine? [board pos] ...) (is (= true (mine? board [2 2]))) (is (= false (mine? board [1 1]))) (is (= false (mine? board [-1 0])))) (with-test (defn neighbours [pos] ...) (is (= [[0 -1] [0 0] [0 1] [1 -1] [1 1] [2 -1] [2 0] [2 1]] (neighbours [0 1]))))