Skip to content

Instantly share code, notes, and snippets.

@marick
Last active August 29, 2015 22:20
Show Gist options
  • Save marick/ec9e8ad4f227e8b33a02 to your computer and use it in GitHub Desktop.
Save marick/ec9e8ad4f227e8b33a02 to your computer and use it in GitHub Desktop.
A Specter Showcase

Finding all values of :b in the maps inside a vector inside a map inside a vector:

     user=> (def x [{:a [{:b 1} {:b 2} {:a -30}]}
                         {}
                         {:a [{:b 3}]}])
     user=> (select [ALL :a ALL :b] x)
     [1 2 nil 3]

Replacing vectors of numbers with their sums:

      user=> (def x [{:a [1 2 3]}
                     {:a [3 4 5]}])
      user=> (transform [ALL :a] (partial apply +) x)
      [{:a 6} {:a 12}]

Summing vectors, but leaving lists of numbers alone:

      user=> (def x [{:a [1 2 3]}
                     {:a '(-40 -45)}
                     {:a [4 5 6]}])
      user=> (transform [ALL :a vector?] (partial apply +) x)
      [{:a 6} {:a (-40 -45)} {:a 15}]

Extracting all the vectors from a tree, regardless of nesting level:

      user=> (def x `(list [1 2 3]
                           (concat [4 5 6] [7 8 9])))

      user=> (select (walker vector?) x)
      ([1 2 3] [4 5 6] [7 8 9])

Reversing the first two elements of any vector, ignoring other types:

      user=> (def x (vector "not vector"
                            ["first" "SECOND" 3 4]
                            "not vector"
                            [-11111 2] ])
      user=> (transform [ALL vector? (srange 0 2)] reverse x)
      ["not vector" ["SECOND" "first" 3 4] "not vector" [2 -11111]]

Showing the even values of vectors along with their indices:

      user=> (defn describe-evens [v]
               (->> v
                    (select [(view (partial map-indexed vector)) 
                            ALL
                            (collect-one FIRST)
                            LAST
                            even?])
                    (map (fn [[index val]]
                           (format "index %d has value %d" index val)))))
      user=> (describe-evens [-1 -2 -3 -4])
      ("index 1 has value -2" "index 3 has value -4")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment