;; constantly returns a function which always returns the same value (map (constantly 9) [1 2 3]) user=> (9 9 9) (map (constantly (rand-int 100)) [:a :b :c]) user=> (43 43 43)
(defn constantly
"Returns a function that takes any number of arguments and returns x."
{:added "1.0"}
[x] (fn [& args] x))
Comments top
3 comment(s) for constantly.
any examples of when this would be useful? I think it is weird to want a function that always returns "x" regardless of the number of arguments passed to it - however since this exists in core I'm sure it is sensible, more a case of I've not enough experience to appreciate its value.
I asked about use cases for this function in #clojure and got a good response from amalloy:
Say you want to call a library function that asks you to pass it a function; it's going to call that function ten times with different arguments to decide how to populate a list it gives you. But your program is really simple and you want the list to just be full of zeroes. So you call:
Hope that's useful!
(constantly 1) is often useful when it comes to testing. You can think of it like you would a "stub".