Created
December 25, 2012 03:25
-
-
Save anonymous/4371524 to your computer and use it in GitHub Desktop.
A way to re-order the threading macro
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
;; The ->> threading macro will normally place the previous form into the last argument position of the next form | |
;; However, there are times when you are working with functions that don't take the required parameter in the last spot | |
;; In this example, I'm extracting all path locations before /v | |
;; re-seq first and second all work with the threading macro | |
;; However, when it comes time to split the string result, clojure.string/split takes two arguments | |
;; The first is the string, and the second is the regular expression to split on. | |
;; For the threading macro to work as is, these arguments need to be reversed | |
;; One way of doing this is creating an anonymous function that does this | |
;; #(clojure.string/split % #"/") This is the function | |
;; Then you actually evaluate by wrapping it in paranthesis | |
;; (#(clojure.string/split % #"/")) This returns the anonymous function which takes a single argument, the string | |
;; The threading macro then threads the previous string into this function, allowing the threading macro to still work | |
(->> "/a/file/loc/to/Somewhere/v/dont/include/these/" | |
(re-seq #"^[/]([-/_A-Za-z0-9]+)/v/") ; Get all parts before /v | |
first ;; Sequence returns in this form ( (total string) (additional sequences match)), first removes the wrapping list | |
second ;; So that you can grab the second item in the list | |
(#(clojure.string/split % #"/")) ;; Split them into tags using / as a separator | |
) | |
;; Returns ["a" "file" "loc" "to" "somewhere"] | |
;; By using this anonymous function pattern you can use functions that may not normally be useable with the threading macro | |
;; For example, a function might need the threading argument in the third position of a 5 argument function: | |
;; (#(some-fn param1 param2 param3 % param4)) | |
;; This pattern will also work with the -> threading macro |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment