├── .travis.yml ├── tracks.jpg ├── doc └── intro.md ├── .gitignore ├── project.clj ├── klipse ├── klipse.html └── klipse.md ├── CHANGELOG.md ├── src └── tracks │ └── core.cljc ├── test └── tracks │ └── core_test.clj ├── README.md └── LICENSE /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | 3 | jdk: 4 | - openjdk8 5 | -------------------------------------------------------------------------------- /tracks.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/escherize/tracks/HEAD/tracks.jpg -------------------------------------------------------------------------------- /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to tracks 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/what-to-write/) 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .hgignore 11 | .hg/ 12 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject tracks "1.0.6" 2 | :description "Shape based programming" 3 | :url "https://github.com/escherize/tracks" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.9.0"]] 7 | :profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"] 8 | [viebel/codox-klipse-theme "0.0.1"]]}} 9 | :jvm-opts ["-XX:-OmitStackTraceInFastThrow"]) 10 | -------------------------------------------------------------------------------- /klipse/klipse.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | (def a 42) 10 | a 11 |

12 | (ns my.combinatorics
13 |  (:require [clojure.math.combinatorics :refer [permutations]]))
14 | 
15 | (permutations [1 2 3 a])
16 |     
17 |

18 | (ns my.namespace
19 |  (:require [tracks.core :refer [deftrack]]))
20 | 
21 | (deftrack a {:a to-b} {:b to-b})
22 | 
23 | (a {:a 1})
24 |     
25 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. This change log loosely follows the conventions of [keepachangelog.com](http://keepachangelog.com/). 3 | 4 | ## [1.0.1] - 2016-1-17 5 | ### Breaking Changes 6 | - `track` is now a thin layer over let + I reccomend using track/let more often. 7 | 8 | ## [0.1.7] - 2016-11-03 9 | ### Breaking Changes 10 | - `track` is now a macro and works only with symbols 11 | ### Added 12 | - `track` is now implemented in terms of let 13 | 14 | 15 | ## [0.1.5] - 2016-11-03 16 | ### Added 17 | - `tracks.core/let` - let macro! 18 | 19 | ## [0.1.4] - 2016-10-16 20 | ### Added 21 | - Tracks now runs on ClojureScript! 22 | ### Removed 23 | - `tracks.core/tracks` is no longer an alias for `tracks.core/track` 24 | 25 | ## [0.1.3] - 2016-10-08 26 | ### Fixed 27 | - Make tracks non-destructive, i.e. do not edit keys that are not operated on. 28 | ### Changed 29 | - Improve docs 30 | 31 | ## [0.1.2] - 2016-10-04 32 | ### Added 33 | - Added optional function-map to tracks. 34 | ### Changed 35 | - Improve docs 36 | 37 | 38 | ## [0.1.0] - 2016-10-04 39 | ### Changed 40 | - First relase of tracks 41 | -------------------------------------------------------------------------------- /src/tracks/core.cljc: -------------------------------------------------------------------------------- 1 | (ns tracks.core 2 | (:refer-clojure :exclude [let])) 3 | 4 | (defn symbol-paths 5 | ([x] (symbol-paths x [])) 6 | ([x p] 7 | (into [] 8 | (cond 9 | (symbol? x) {x p} 10 | (map? x) (mapcat #(symbol-paths (val %) (conj p (key %))) x) 11 | (sequential? x) (apply concat (map-indexed #(symbol-paths %2 (conj p %1)) x)) 12 | :else {x p})))) 13 | 14 | (defn path->value [p x] 15 | (if (empty? p) 16 | x 17 | (recur (next p) 18 | (if (sequential? x) 19 | (nth x (first p)) 20 | (get x (first p)))))) 21 | 22 | (defmacro assert-args 23 | [& pairs] 24 | `(do (when-not ~(first pairs) 25 | (throw (IllegalArgumentException. 26 | (str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form)))))) 27 | ~(clojure.core/let [more# (nnext pairs)] 28 | (when more# 29 | (list* `assert-args more#))))) 30 | 31 | (defmacro let [bindings & body] 32 | (assert-args 33 | (vector? bindings) "a vector for its binding" 34 | (even? (count bindings)) "an even number of forms in binding vector") 35 | (let* [paths (->> bindings 36 | (partition 2) 37 | (map (fn [[tpatt input]] 38 | [(gensym) tpatt input])) 39 | (mapcat 40 | (fn [[sym tpatt input]] 41 | (->> tpatt 42 | symbol-paths 43 | (mapcat 44 | (fn [[k v]] 45 | [k `(path->value ~v ~sym)])) 46 | (concat [sym input])))) 47 | vec)] 48 | `(let* ~paths ~@body))) 49 | 50 | (defmacro track [in & outs] 51 | `(fn [x#] 52 | (let [~in x#] ~@outs))) 53 | 54 | (defn- invert-map [m] 55 | (reduce 56 | (fn [acc [k v]] 57 | (assoc acc 58 | (if (map? v) (invert-map v) v) 59 | k)) 60 | {} m)) 61 | 62 | (defmacro deftrack [name in & outs] 63 | `(do 64 | (def ~name (track ~in ~@outs)) 65 | (alter-meta! (var ~name) merge {:arglists (list [(~invert-map '~in)]) 66 | :tracks/expects '~in}) 67 | ~name)) 68 | -------------------------------------------------------------------------------- /test/tracks/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns tracks.core-test 2 | (:require [clojure.test :refer :all] 3 | [tracks.core :as t :refer :all :exclude [let]] 4 | [clojure.test.check :as tc] 5 | [clojure.test.check.generators :as g] 6 | [clojure.test.check.properties :as prop] 7 | [clojure.test.check.clojure-test :refer [defspec]])) 8 | 9 | (def scalar (g/one-of [g/char g/int g/string-alphanumeric g/keyword])) 10 | 11 | (def ^:dynamic *trial-count* 100) 12 | 13 | (def shallow-data-gen 14 | (g/one-of 15 | [(g/vector scalar) (g/list scalar) (g/map scalar scalar)])) 16 | 17 | (def shallow-map-gen 18 | (g/such-that #(and (not-empty %) 19 | (= (count (vals %)) 20 | (count (set (vals %))))) 21 | (g/map scalar scalar) 22 | ;; 100 tries not 10. 23 | 100)) 24 | 25 | (defspec shallow-maps-shuffled-keys 26 | *trial-count* 27 | (prop/for-all [m shallow-map-gen] 28 | (let [map-two (zipmap (shuffle (keys m)) (vals m))] 29 | (= map-two ((track m map-two) m))))) 30 | (deftest t-let 31 | (testing "one binding" 32 | (is (= 1 (t/let [{:a a} {:a 1}] a)))) 33 | 34 | (testing "deep binding" 35 | (is (= "ABCD" 36 | (t/let [{:a {:b {:c {:d abcd}}}} {:a {:b {:c {:d "ABCD"}}}}] abcd)))) 37 | 38 | (testing "multiple bindings" 39 | (is (= 2 (t/let [{:a a} {:a 1} 40 | b (+ a a)] 41 | b))))) 42 | 43 | (deftest tracks-works 44 | (testing "can move keys" 45 | (is (= {:b "!!"} 46 | ((track {:a value} {:b value}) 47 | {:a "!!"})))) 48 | 49 | (testing "swap vectors" 50 | (is (= [:a :b] ((track [f s] [s f]) [:b :a]))) 51 | (is (= [:a :c :b] ((track [f s t] [f t s]) [:a :b :c])))) 52 | 53 | (testing "can move + swap vectors" 54 | (let [a-to-b-and-reverse (track {:a [f s]} {:b [s f]})] 55 | (is (= {:b [1 0]} 56 | (a-to-b-and-reverse {:a [0 1]})))))) 57 | 58 | (deftest rotation 59 | (let [rotate-players (track {:active-player a :players [b c d]} 60 | {:active-player b :players [c d a]}) 61 | initial-game {:active-player {:name "A"} ;;<- note the more complex leaf! 62 | :players [{:name "B"} 63 | {:name "C"} 64 | {:name "D"}]} 65 | game (atom initial-game)] 66 | (is (= initial-game @game)) 67 | (swap! game rotate-players) 68 | (is (= {:active-player {:name "B"} 69 | :players [{:name "C"} 70 | {:name "D"} 71 | {:name "A"}]} @game)) 72 | (swap! game rotate-players) 73 | (swap! game rotate-players) 74 | (swap! game rotate-players) 75 | (is (= initial-game @game)))) 76 | 77 | (deftest testing-let 78 | (is (= "Hi Hello!!!???" 79 | (t/let [{:a hi :b hello :c [one two]} {:a "Hi" :b "Hello" :c ["!!" "???"]} 80 | {:punk punk} {:punk "!"}] 81 | (str hi " " hello punk one two)))) 82 | 83 | (is (= "Hello World!" 84 | (let [bang "!"] 85 | (t/let [{:a hi :b hello} {:a "Hello" :b "World"} 86 | {:punk punk} {:punk bang}] 87 | (str hi " " hello punk))))) 88 | 89 | (testing "going deeper" 90 | (is (= "Hello World!" 91 | (let [bang "!"] 92 | (t/let [{:a [_ _ _ _ hi] 93 | :b {:d {:e {:f [_ _ hello]}}}} 94 | {:a [0 1 2 3 "Hello"] 95 | :b {:d {:e {:f ["ignore" "me" "World"]}}}} 96 | {:punk punk} {:punk bang}] 97 | (str hi " " hello punk)))))) 98 | (is (nil? (t/let []))) 99 | (is (= 1 (t/let [a 1] a))) 100 | (is (nil? (t/let [a 10])))) 101 | 102 | (deftest multi-track 103 | (is (= [1 1 1] ((track [x] [x x x]) [1]))) 104 | (is (= [2 2 2] ((track [x] [x x x]) [2]))) 105 | (is (= [1 0 1 0] ((track [x y] [x y x y]) [1 0]))) 106 | (is (= {:b "ayee", :c "ayee"} 107 | ((track {:a a} {:b a :c a}) {:a "ayee"}))) 108 | (is (= {:a "ayee+ayee", :b "ayee", :c "ayee"} 109 | ((track {:a a} {:a (str a "+" a) :b a :c a}) {:a "ayee"})))) 110 | 111 | (deftest deftrack-test 112 | (try (deftrack ab {:a pop-me} {:b pop-me}) 113 | (is (= {:b "???"} (ab {:a "???"}))) 114 | (finally (ns-unmap *ns* 'ab)))) 115 | 116 | 117 | (deftest shallow-arglists-metadata 118 | (try (deftrack ab {:a pop-me} {:b pop-me}) 119 | (is (= '([{pop-me :a}]) (:arglists (meta #'ab)))) 120 | (finally (ns-unmap *ns* 'ab)))) 121 | 122 | (deftest deep-arglists-metadata 123 | (try (deftrack move-some-keys 124 | {:a a :b b :c c :d {:e e}} 125 | {:a b :b c :c e :d {:e a}}) 126 | (is (= '([{a :a, b :b, c :c, {e :e} :d}]) 127 | (:arglists (meta #'move-some-keys)))) 128 | (finally (ns-unmap *ns* 'move-some-keys)))) 129 | 130 | (deftest deep-tracks-expects-metadata 131 | (try (deftrack move-some-keys 132 | {:a a :b b :c c :d {:e e}} 133 | {:a b :b c :c e :d {:e a}}) 134 | (is (= '{:a a, :b b, :c c, :d {:e e}} 135 | (:tracks/expects (meta #'move-some-keys)))) 136 | (finally (ns-unmap *ns* 'move-some-keys)))) 137 | -------------------------------------------------------------------------------- /klipse/klipse.md: -------------------------------------------------------------------------------- 1 | # tracks 2 | 3 | ## Example based coding 4 | 5 | ![Converging Tracks](https://raw.githubusercontent.com/escherize/tracks/master/tracks.jpg) 6 | 7 | > We become what we behold. We shape our tools, and thereafter our tools shape us. 8 | 9 | > ― Marshall McLuhan 10 | 11 | [![Clojars Project](https://img.shields.io/clojars/v/tracks.svg)](https://clojars.org/tracks) [![Build Status](https://travis-ci.org/escherize/tracks.svg?branch=master)](https://travis-ci.org/escherize/tracks) 12 | 13 | ## Usage 14 | 15 | Add the following line to your leiningen dependencies: 16 | 17 | Require tracks in your namespace header: 18 | 19 | (:require [tracks.core :as t :refer [track]]) 20 | 21 | ```klipse 22 | (require '[tracks.core :refer-macros [deftrack track]]) 23 | (require-macros '[tracks.core :as t]) 24 | ``` 25 | 26 | ## Rationale 27 | 28 | This is a library dedicated to the concept of *shape*. 29 | 30 | shape n. 31 | - the external form, contours, or outline of something. 32 | - the correct or original form or contours of something. 33 | - an example of something that has a particular form. 34 | 35 | shape v. 36 | - to give definite form, organization, or character to. 37 | - fashion or form. 38 | 39 | It's common to grapple with large maps whose shapes are uncomfortable to reason about. 40 | 41 | `tracks` simplifies transformations and destructuring of Clojure datastructures. Instead of describing how to do a transformation, tracks allows the user to create those transformations by __example__. This makes writing complex code that takes one shape and transforms them to another *dead simple*. 42 | 43 | ## Examples 44 | 45 | ### track/let 46 | 47 | Destructuring complex nested data structures can be a real pain. Tracks makes this easy. Much like `clojure.core/let`, symbols in the track pattern will be bound to the value and available the body. Unlike `clojure.core/let` we supply a binding form of *the same shape* as the data we are interested in. 48 | 49 | ```klipse 50 | 51 | (t/let [{:a {:b [greeting person]}} ;;<- binding form 52 | {:a {:b ["Hello" "World"]}} ;;<- data we want to get at 53 | ] 54 | (str greeting " " person "!")) 55 | 56 | ;;=> "Hello World!" 57 | 58 | (t/let [{:a {:b x} :c {:d y}} 59 | {:a {:b 1} :c {:d 2}}] 60 | (+ x y)) 61 | 62 | ;;=> 3 63 | 64 | ``` 65 | ### track/track for building functions 66 | 67 | `track` returns a function which takes data of the shape of its first argument. 68 | 69 | Below, the function returned by `track` will take a map with keys `:a` and `:b` and move the value at `:a` to `:b`, and the value at `:b` to `:a`: 70 | 71 | ``` clojure 72 | (track {:a one :b two} 73 | {:a two :b one}) 74 | 75 | ;;=> anonymous fn 76 | 77 | (def swap-a-b (track {:a one :b two} 78 | {:a two :b one})) 79 | (swap-a-b {:a 100 :b 3000}) 80 | 81 | ;;=> {:a 3000 :b 100} 82 | ``` 83 | 84 | `deftrack` does the same thing, but binds it too: 85 | 86 | ``` clojure 87 | (deftrack swap-a-b {:a one :b two} {:a two :b one}) 88 | (swap-a-b {:a 100 :b 3000}) 89 | 90 | ;;=> {:a 3000 :b 100} 91 | ``` 92 | 93 | We can move positions in vectors and deeply nested maps in exactly the same way: 94 | 95 | ```klipse 96 | ((track {:a [zero one]} 97 | {:b [one zero]}) 98 | {:a [:zero :one]}) 99 | 100 | ;; => {:b [:one :zero]} 101 | ``` 102 | 103 | ### Arbitrary nesting levels 104 | 105 | Deep thinking about deepy nested shapes is a bygone era: 106 | 107 | ``` clojure 108 | (deftrack deeptx 109 | {0 zero, 1 one, 2 two, 3 three} ;; <- deeptx takes a map with this shape 110 | {:a zero :b {:c one :d {:e two :f {:g three}}}} ;; <- deeptx then returns one with this shape 111 | ) 112 | 113 | (deeptx {0 "first" 1 "second" 2 "third" 3 "fourth"}) 114 | ;;=> {:a "first", :b {:c "second", :d {:e "third", :f {:g "fourth"}}}} 115 | ``` 116 | ### Complex leaf values 117 | 118 | `track` greatly simplifies rotating values, too: 119 | 120 | Let's simulate a game where there's an active player, and all other players wait in line to become the active one. Once a player has played their turn, they go to the back of the line. 121 | 122 | ```klipse 123 | ;;; Setup the function that moves around players, 124 | ;;; no matter what datastructure the players are 125 | ;;; represented as: 126 | 127 | (deftrack move-players 128 | {:active-player p1 :players [p2 p3 p4]} 129 | {:active-player p2 :players [p3 p4 p1]}) 130 | ``` 131 | ```klipse 132 | ;;; Here's the datastructure that represents the state of the game. 133 | ;;; Notice that the players are more than scalar values! 134 | 135 | (defonce game (atom {:active-player {:name "A"} 136 | :players [{:name "B"} 137 | {:name "C"} 138 | {:name "D"}]})) 139 | @game 140 | ``` 141 | ```klipse 142 | (swap! game move-players) 143 | 144 | @game 145 | ``` 146 | ```klipse 147 | (swap! game move-players) 148 | @game 149 | ``` 150 | ```klipse 151 | (swap! game move-players) 152 | @game 153 | ``` 154 | 155 | ### Multiple endpoints 156 | 157 | Like a train track, sometimes one track can split into many. With `track` the values can be duplicated. 158 | 159 | ``` clojure 160 | (deftrack one-to-many x {:a x :b {:c [x x]}}) 161 | 162 | (one-to-many "?") 163 | 164 | ;;=> {:a "?", :b {:c ["?" "?"]}} 165 | ``` 166 | ## How it works 167 | 168 | `track` is implemented in terms of `let` 169 | 170 | ``` clojure 171 | (def move-a-key (track {:x one} {:y one})) 172 | 173 | (move-a-key {:x "MoveMe"}) 174 | 175 | ;;=> {:y "MoveMe"} 176 | 177 | (move-a-key {:x [:a :b :c]}) 178 | 179 | ;;=> {:y [:a :b :c]} 180 | ``` 181 | 182 | We see it moves any value from keypath [:x] to keypath [:y]. 183 | 184 | The way it does it is by moving `{:x one}` into a `let` like so: 185 | 186 | ``` clojure 187 | ;; vvvvvvvv---- this is the first arg to track 188 | (tracks/let [{:x one} input] 189 | ;; so now one is bound to (get input :x) 190 | ;; vvvvvv---- this is the 2nd arg to track 191 | {:y one}) 192 | ``` 193 | 194 | ## Want more examples? 195 | 196 | Check the test namespace! 197 | 198 | ## License 199 | 200 | Copyright © 2016 Bryan Maass 201 | 202 | Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tracks 2 | 3 | ## Example based coding 4 | 5 | ![Converging Tracks](https://raw.githubusercontent.com/escherize/tracks/master/tracks.jpg) 6 | [![Build Status](https://travis-ci.org/escherize/tracks.svg?branch=master)](https://travis-ci.org/escherize/tracks) 7 | 8 | > We become what we behold. We shape our tools, and thereafter our tools shape us. 9 | 10 | > ― Marshall McLuhan 11 | 12 | ## Usage 13 | 14 | Add the following line to your leiningen dependencies: 15 | 16 | [![Clojars Project](https://img.shields.io/clojars/v/tracks.svg)](https://clojars.org/tracks) 17 | 18 | Require tracks in your namespace header: 19 | 20 | (:require [tracks.core :as t :refer [track]]) 21 | 22 | ## Rationale 23 | 24 | This is a library to handle _shapes_. What's a shape? 25 | 26 | shape n. 27 | - the correct or original form or contours of something. 28 | - an example of something that has a particular form. 29 | 30 | shape v. 31 | - to give definite form, organization, or character to. 32 | 33 | It's common to grapple with deeply nested arguments whose shapes are difficult to know without running the code. The data we love, tho pure and immutable can be nested and complex. This approach removes the cognitive burden needed to understand our datastructures. 34 | 35 | ## Examples 36 | 37 | #### deftrack example: 38 | 39 | Instead of describing _how to do a transformation_, tracks allows the user to _create those transformations declaratively_. This makes writing code that takes one shape and transforms them to another *dead simple*. 40 | 41 | Let's consider this data as our input. Typically this shape needs to be 'reverse-engineered' by reading and understanding code with `get-in`, destructuring, and other such operations. 42 | 43 | ``` clojure 44 | (def buyer-information-map 45 | {:buyer-info 46 | {:is-guest true 47 | :primary-contact {:name {:first-name "Bob" :last-name "Ross"} 48 | :phone {:complete-number "123123123"} 49 | :email {:email-address "thebobguy@rossinator.com"}}}}) 50 | ``` 51 | 52 | 53 | Next, Let's create a function that takes this particular _shape_ and returns another representing a notification for a customer. 54 | 55 | 56 | ```clojure 57 | (require '[tracks.core :as t :refer [deftrack]]) 58 | 59 | (deftrack notify-buyer 60 | {:buyer-info {:is-guest guest? ;; 1 61 | :primary-contact {:name {:first-name firstname 62 | :last-name lastname} 63 | :phone {:complete-number phone} 64 | :email {:email-address email}}}} 65 | (when guest? ;; 2 66 | {:command :send-notification 67 | :address email 68 | :phone phone 69 | :text (str "Hi, " firstname " " lastname)})) 70 | ;; => #function[user/notify-buyer] 71 | 72 | (notify-buyer buyer-information-map) 73 | ;; => {:command :send-notification 74 | ;; :address "thebobguy@rossinator.com" 75 | ;; :phone "123123123" 76 | ;; :text "Hi, Bob Ross"} 77 | ``` 78 | 79 | 1. `deftrack` expects data of this shape 80 | 2. `deftrack` returns this value 81 | 82 | ### What is going on here? 83 | 84 | For every symbol in the binding form to `deftrack` (1 above), `deftrack` generates a program to seamlessly write the get / get-in / assoc-in / assoc / etc. sort of accessing code and allows you to focus on __your data__. 85 | 86 | ## Destructuring 87 | 88 | You may be thinking to yourself: Clojure already has destructuring! That's true, let's compare using `deftrack` against `defn` style destructuring: 89 | 90 | ``` clojure 91 | (deftrack notify-buyer 92 | {:buyer-info {:is-guest guest? 93 | :primary-contact {:name {:first-name firstname 94 | :last-name lastname} 95 | :phone {:complete-number phone} 96 | :email {:email-address email}}}} 97 | (when guest? 98 | {:command :send-notification 99 | :address email 100 | :phone phone 101 | :text (str "Hi, " firstname " " lastname)})) 102 | 103 | (defn notify-buyer-2 [{{guest? :is-guest, 104 | {{firstname :first-name, lastname :last-name} :name, 105 | {phone :complete-number} :phone, 106 | {email :email-address} :email} 107 | :primary-contact} 108 | :buyer-info}] 109 | (when guest? 110 | {:command :send-notification 111 | :address email 112 | :phone phone 113 | :text (str "Hi, " firstname " " lastname)})) 114 | ``` 115 | 116 | I think you'd agree which of those is easier to read. 117 | 118 | ### deftrack metadata 119 | 120 | deftrack plays nice with arglists metadata, enabling your editor to explain what sort of shape a function created with `deftrack` takes. 121 | 122 | ``` clojure 123 | (deftrack move-some-keys 124 | {:a a :b b :c c :d {:e e}} 125 | {:a b :b c :c e :d {:e a}}) 126 | 127 | (move-some-keys {:a 1 :b 2 :c 3 :d {:e 4}}) 128 | ;; => {:a 2, :b 3, :c 4, :d {:e 1}} 129 | 130 | (:arglists (meta #'move-some-keys)) 131 | ;; => ([{a :a, b :b, c :c, {e :e} :d}]) 132 | ``` 133 | 134 | Since we don't like to read deeply destructured arglists, `deftracks` also goes one step further, and includes what shape your function _expects_. (Todo: make this work with editors). 135 | 136 | ``` clojure 137 | (:tracks/expects (meta #'move-some-keys)) 138 | ;; => {:a a, :b b, :c c, :d {:e e}} 139 | ``` 140 | 141 | #### let example 142 | 143 | For more flexible flowing of data, here's __tracks/let__, which allows for the same data-oriented style but with multiple arguments, etc. 144 | 145 | ``` clojure 146 | (require '[tracks.core :as t :refer [deftrack]]) 147 | 148 | ;; Please Notice: you usually don't get to see what some-data looks like! :) 149 | (def some-data 150 | {:more-info {:price-for-this-order 10} 151 | :order-info {:amount-bought-from-my-company 3}}) 152 | 153 | ;;in another part of your program: 154 | 155 | 156 | ;; you can use t/let: 157 | (t/let [{:more-info {:price-for-this-order price} 158 | :order-info {:amount-bought-from-my-company quantity}} some-data] 159 | (* price quantity)) 160 | ;;=> 30 161 | 162 | ;; or you can use deftrack: 163 | (deftrack calculate-price-for-order 164 | {:more-info {:price-for-this-order price} 165 | :order-info {:amount-bought-from-my-company quantity}} 166 | (* price quantity)) 167 | 168 | (calculate-price-for-order some-data) 169 | ;;=> 30 170 | ``` 171 | 172 | ### Arbitrary nesting levels 173 | 174 | Deep contemplation about deeply nested shapes is the old way. 175 | 176 | ``` clojure 177 | (deftrack deeptx 178 | {0 zero 179 | 1 one 180 | 2 two 181 | 3 three} ;; <- deeptx takes a map with this shape 182 | {:a zero 183 | :b {:c one 184 | :d {:e two 185 | :f {:g three}}}} ;; <- deeptx then returns one with this shape 186 | ) 187 | 188 | (deeptx {0 "first" 1 "second" 2 "third" 3 "fourth"}) 189 | ;;=> {:a "first", :b {:c "second", :d {:e "third", :f {:g "fourth"}}}} 190 | ``` 191 | 192 | ### Complex leaf values 193 | 194 | Let's simulate a game where there's an active player, and all other players wait in a queue to become the active one. Once a player has played their turn, they naturally go to the back of the queue. 195 | 196 | ```clojure 197 | 198 | ;;; Setup the function that moves around players, 199 | ;;; no matter what datastructure the players are 200 | ;;; represented as: 201 | 202 | (deftrack move-players 203 | {:active-player p1 :players [p2 p3 p4]} 204 | {:active-player p2 :players [p3 p4 p1]}) 205 | 206 | ;;; Here's the datastructure that represents the state of the game. 207 | ;;; Notice that the players are more than scalar values! 208 | 209 | (defonce game (atom {:active-player {:name "A"} 210 | :players [{:name "B"} 211 | {:name "C"} 212 | {:name "D"}]})) 213 | 214 | (swap! game move-players) 215 | ;;=> {:active-player {:name "B"} 216 | ;; :players [{:name "C"} 217 | ;; {:name "D"} 218 | ;; {:name "A"}]} 219 | 220 | (swap! game move-players) 221 | ;;=> {:active-player {:name "C"} 222 | ;; :players [{:name "D"} 223 | ;; {:name "A"} 224 | ;; {:name "B"}]} 225 | 226 | 227 | (swap! game move-players) 228 | ;;=> {:active-player {:name "D"} 229 | ;; :players [{:name "A"} 230 | ;; {:name "B"} 231 | ;; {:name "C"}]} 232 | 233 | ``` 234 | 235 | ### Multiple endpoints 236 | 237 | Like a train track, sometimes one track can split into many. With `track` the values can be duplicated. 238 | 239 | ``` clojure 240 | (deftrack one-to-many {:clone-me x} {:a x :b {:c [x x]}}) 241 | 242 | (one-to-many {:clone-me "?"}) 243 | 244 | ;;=> {:a "?", :b {:c ["?" "?"]}} 245 | ``` 246 | 247 | ## Want more examples? 248 | 249 | Check the test namespace! 250 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | --------------------------------------------------------------------------------