Imagine we have a string " I will be a url slug ", and we want to transform it into a valid "url". Let's build a slugify function to do this transformation.
(defnslugify[string](clojure.string/replace(clojure.string/lower-case(clojure.string/trimstring))#" ""-"))(slugify" I will be a url slug ");; "i-will-be-a-url-slug"
Here we have:
trim: removes whitespace from both ends of string
lower-case: converts string to all lower-case
replace: replaces all instance of match with replacement in a given string
Another solution is to use the threading macro. Basically we can compose functions using the -> operator.
(defnslugify[string](->string(clojure.string/trim)(clojure.string/lower-case)(clojure.string/replace#" ""-")))(slugify" I will be a url slug ");; "i-will-be-a-url-slug"
In Clojure, I really like the
threading macro
.Imagine we have a string
" I will be a url slug "
, and we want to transform it into a valid "url". Let's build aslugify
function to do this transformation.Here we have:
Another solution is to use the threading macro. Basically we can compose functions using the -> operator.
Beautiful!
PS. another solution is to compose all function using
comp
function :)PS2. I wrote a post about Functional Programming with Clojure
It's nice not having to work backwards:
instead of
I once wrote something to let you do this in Python:
Python had the idea that methods are just functions (hence having an explicit
self
parameter), it just didn't take it far enough.