Skip to content

clojure.core/constantly

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 4 Runnable: 3
([x])

Returns a function that takes any number of arguments and returns x.

Examples

by pkolloch on . May have evaluation errors.
by shockbob on
by john.r.woodward on
by icemaze on

Note by ossareh

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.

Note by clizzin

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!

Note by devn

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

Note by phreed

constantly is typically used as an argument to a higher order function when a constant value is needed.

Note by jmglov

It is also quite useful in unit tests:

(deftest foo
  (testing "Clojure tweets only"
    (with-redefs [twitter/get-tweets
                  (constantly ["#clojure is awesome!" "Yay! #winning"])]
      (is (= ["#clojure is awesome!"]
             (only-clojure "@happyguy"))))))

Note by dexterous

Basically, when you already know the result of a function that you would need to pass to a higher order function, you can simply wrap it in a constantly to avoid creating a variadic anonymous function.

(defn hof [f]
  (do-something-with (f ...))

(def x "result")

(hof (constantly x))

Note by bradleesand

I've used this to create a no-op function.

(let [handler (if (some? value)
                 #(do-something-with value)
                 ; else no-op
                 (constantly nil))]
  ; call handler
  (handler "foo" "bar"))

Note by defHLT

Just a shortcut to

(fn [& args] x)

Note by eneroth

Just a shortcut to…

Note that it's not the same as (fn [& args] x). constantly will eagerly evaluate the code in the closure to provide a constant return value, as the name implies.

(constantly (println :hello))
;; :hello
;; => #function[clojure.core/constantly/fn--5759]

(fn [& args] (println :hello))
;; => #function[…/eval712692/f--712693]

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.