You're viewing version 1.2.0 of constantly. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16



  • (constantly x)
Returns a function that takes any number of arguments and returns x.

3 Examples top

  • user=> (def boring (constantly 10))
    user=> (boring 1 2 3)
    user=> (boring)
    user=> (boring "Is anybody home?")
  • ;; A really goofy way to find the size of a collection
    user=> (reduce + (map (constantly 1) [:a :b :c]))
  • ;; 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)
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:1112 top

(defn constantly
  "Returns a function that takes any number of arguments and returns x."
  {:added "1.0"}
  [x] (fn [& args] x))
Vars in clojure.core/constantly: defn fn

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:

(libfn (constantly 0))

Hope that's useful!

(constantly 1) is often useful when it comes to testing. You can think of it like you would a "stub".

Log in to add a comment.