Skip to content

Instantly share code, notes, and snippets.

@francisluong francisluong/;-)-repl.clj
Last active Jul 13, 2017

Embed
What would you like to do?
user=> (def c [{:next-hop "192.168.1.1", :prefix "172.16.1.1/32", :route-status "*|e"}
#_=> {:next-hop "192.168.255.255", :prefix nil, :route-status "*>e"}])
#'user/c
user=>
user=> (let [prev (atom nil)]
#_=> (map (fn [r]
#_=> (if (and @prev (not (:prefix r)))
#_=> (assoc r :prefix @prev)
#_=> (do (reset! prev (:prefix r))
#_=> r)))
#_=> c))
({:next-hop "192.168.1.1", :prefix "172.16.1.1/32", :route-status "*|e"}
{:next-hop "192.168.255.255", :prefix "172.16.1.1/32", :route-status "*>e"})
user=>
user=> (second
#_=> (reduce
#_=> (fn [[prev acc] v]
#_=> (if (and prev (not (:prefix v)))
#_=> [prev (conj acc (assoc v :prefix prev))]
#_=> [(:prefix v) (conj acc v)]))
#_=> [nil []]
#_=> c))
[{:next-hop "192.168.1.1", :prefix "172.16.1.1/32", :route-status "*|e"}
{:next-hop "192.168.255.255", :prefix "172.16.1.1/32", :route-status "*>e"}]
user=>
user=> (loop [prev nil
#_=> acc []
#_=> coll c]
#_=> (if-let [v (first coll)]
#_=> (if (and prev (not (:prefix v)))
#_=> (recur prev (conj acc (assoc v :prefix prev)) (rest coll))
#_=> (recur (:prefix v) (conj acc v) (rest coll)))
#_=> acc))
[{:next-hop "192.168.1.1", :prefix "172.16.1.1/32", :route-status "*|e"}
{:next-hop "192.168.255.255", :prefix "172.16.1.1/32", :route-status "*>e"}]
user=>
(def c [{:next-hop "192.168.1.1", :prefix "172.16.1.1/32", :route-status "*|e"}
{:next-hop "192.168.255.255", :prefix nil, :route-status "*>e"}])
; map with atom
(let [prev (atom nil)]
(map (fn [r]
(if (and @prev (not (:prefix r)))
(assoc r :prefix @prev)
(do (reset! prev (:prefix r))
r)))
c))
; reduce with compound accumulator
(second
(reduce
(fn [[prev acc] v]
(if (and prev (not (:prefix v)))
[prev (conj acc (assoc v :prefix prev))]
[(:prefix v) (conj acc v)]))
[nil []]
c))
; loop/recur
(loop [prev nil
acc []
coll c]
(if-let [v (first coll)]
(if (and prev (not (:prefix v)))
(recur prev (conj acc (assoc v :prefix prev)) (rest coll))
(recur (:prefix v) (conj acc v) (rest coll)))
acc))
*|e172.16.1.1/32 192.168.1.1 0 65535 i
*>e 192.168.255.255 0 65535 i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.