Advertisement
Guest User

-> and reduce

a guest
Jan 31st, 2015
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (require '[com.stuartsierra.dependency :as dep])
  2.  
  3. (-> (dep/graph)
  4.   (dep/depend :b :a)   ; "B depends on A"
  5.   (dep/depend :c :b)   ; "C depends on B"
  6.   (dep/depend :c :a)   ; "C depends on A"
  7.   (dep/depend :d :c)
  8.   (dep/topo-sort))
  9.  
  10. ; Some new edges we want to add the the graph.
  11. (def new-edges [[:b :a] [:c :b] [:c :a] [:d :c]])
  12.  
  13. ; dep/depend is cumbersome when you have edge tuples.
  14. (defn add-edge [g e]
  15.   (apply dep/depend g e))
  16.  
  17. ; Add and get topological sorting.
  18. (dep/topo-sort (reduce add-edge (dep/graph) new-edges))
  19.  
  20. ; Rewrite to threading again.
  21. ; Note that the (#(...)) trick doesn't play well with
  22. ; functions like reduce, map, etc when the function they
  23. ; take is written using #(...).
  24. (-> (dep/graph)
  25.   (#(reduce add-edge % new-edges))
  26.   dep/topo-sort)
  27.  
  28. ; Use reduce' instead.
  29. (defn reduce' [x f ys]
  30.   (reduce f x ys))
  31.  
  32. ; Works well with ->.
  33. (-> (dep/graph)
  34.   (reduce' add-edge new-edges)
  35.   (dep/topo-sort))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement