Last active
December 19, 2015 12:39
-
-
Save astynax/5956370 to your computer and use it in GitHub Desktop.
Примеры работы со структурами данных в Clojure
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
;; некая "сложная" структура данных для примера | |
(def shapes | |
[{:shape {:type :line | |
:path [{:x 10 :y 10} | |
{:x 100 :y 100}]} | |
:pen {:color "FF00FF" | |
:style :solid}} | |
{:shape {:type :dot | |
:path [{:x 200 :y 200}]} | |
:pen {:color :red}}]) | |
;; базовые структуры данных | |
(def point {:x 100 :y 150}) ; словарь | |
(def nums [1 2 3]) ; вектор | |
(def primes #{1 3 5 7 11}) ; множество (set) | |
;; извлечение элементов | |
(get point :x) | |
(get point :z) | |
(get point :z 0) | |
(get nums 1) | |
;; структуры, как функции! | |
(point :x) ; словарь, это функция выборки по ключу | |
(point :z 0) | |
(num 0) ; вектор, это функция выборки по позиции | |
(primes 7) ; множество - функция-предикат, проверяющая вхождение некоего элемента в множество | |
(primes 6) | |
(def yes? #{"Y" "y" "Д" "д"}) | |
(if (yes? "y") "YES!" "NO!") ; множество, как предикат! | |
;; keywords - функции для словарей! | |
(:x point) | |
(:z point -1) | |
;; применение в ФВП | |
(map point [:x :y :z]) | |
(map nums [0 2 1]) | |
(filter primes (range 12 0 -1)) | |
(map :x [point {:x 200 :y 100} {}]) ; селектор! | |
(let [set-1 #{1 2 3 4 5} | |
set-2 #{2 4 6 8 10}] | |
(filter set-1 set-2)) ; пересечение двух множеств! | |
;; некоторые функции для работы со структурами данных | |
(get-in shapes [0 :pen :color]) | |
(get-in shapes [1 :pen :style] :none) | |
(def new-shapes ; в Clojure структуры - immutable, поэтому изменения будут доступны по новой имени | |
(assoc-in shapes [1 :pen :style] :thin)) | |
(get-in new-shapes [1 :pen :style] :none) | |
(get-in new-shapes [0 :shape :path 0 :x]) | |
(def newest-shapes | |
(update-in new-shapes [0 :shape :path 0 :x] + 42)) | |
(get-in newest-shapes [0 :shape :path 0 :x]) | |
(assoc-in {} [:a :b :c] 42) ; создание вглубь! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment