re: What's a useful programming language feature or concept that a lot of languages don't have? VIEW POST


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 a slugify function to do this transformation.

(defn slugify
      (clojure.string/trim string)) #" " "-"))

(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.

(defn slugify
  (-> string
      (clojure.string/replace #" " "-")))

(slugify " I will be a url slug   ") ;; "i-will-be-a-url-slug"


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:

"Take the string, then do x to it, then do y to it"

instead of

"Take the result doing z to the result of doing y to the result of doing x to the string".

I once wrote something to let you do this in Python:

def incd(x, by=1):
    return x + by

print('7 ==', fv(1).incd().incd(2).incd(by=3))
#=>  7 == 7

Python had the idea that methods are just functions (hence having an explicit self parameter), it just didn't take it far enough.

code of conduct - report abuse