-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequence-abstraction.clj
52 lines (27 loc) · 1.27 KB
/
sequence-abstraction.clj
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
;; map, reduce
;; take a sequence/seq
;; the seq library
;; seq functions
;; a data structur "implements" a sequence abstraction
;; lists, vectors, sets, maps
(defn exclamat [x] (str x "!"))
(map exclamate ["A" "B"]) ;; => ("A!" "B!")
(map exclamate ["A" "B"]) ;; => ("A!" "B!")
(map exclamate #{"A" "B"}) ;; => ("A!" "B!")
(map #(exclamate (second %)) {:A "A" :B :B"}) ;; => ("A!" "B!")
;; implementation of linked list in javascript
;; with cons first rest
;; seq does an indirection
(seq '(1 2 3)) ;; => (1 2 3)
(seq [1 2 3]) ;; => (1 2 3)
(seq #{1 2 3}) ;; => (1 2 3)
(seq {:a "a" :b "b"}) ;; => ([:a "a"] [:b "b"])
;; convert seq back to map
(into {} (seq {:a 1 :b 2 :c 3})) ;; => {:a 1 :b 2 :c 3}
;; seq functions apply seq on their args
;; reduce filter distinct group-by and dozens more
;; concentrat on what we can do with a data structure and ignore its implementations
;; program to abstractions - and become implementation-independent!
;; map
(map inc [1 2 3]) ;; => (2 3 4)
(map str ["a" "b" "c"] ["A" "B" "C"]) ;; => ("aA" "bB" "cC")