John Wang
John Wang

Reputation: 4692

In Clojure, what is the idiomatic way to define anonymous function with argument not used?

Instead of:

(run-jetty (fn [request] (response "hello")) 6789)

I want (to ignore the give parameter):

(run-jetty #(response "hello") 6789)

I.e., I want to use anonymous function to save a few typing. Clearly it will raise error at runtime as the the anonymous function will be given a parameter(i.e., request) which it doesn't want to handle . So what is the idiomatic way to achieve that ?

Upvotes: 1

Views: 257

Answers (2)

John Wang
John Wang

Reputation: 4692

I found my question is duplicated with this one.

Also I found the constantly is really constant : It will cache the result for the subsequence usage. Although it's not what I want, it's good to know:

demo1.core=> (defn foo [] (rand))
#'demo1.core/foo
demo1.core=> (def aa (constantly (foo)))
#'demo1.core/aa
demo1.core=> (aa)
0.8006471724049917
demo1.core=> (aa 1)
0.8006471724049917
demo1.core=> (aa 1 2)
0.8006471724049917

Just in case somebody else like me are looking for same thing.

Upvotes: 3

mange
mange

Reputation: 3212

It depends on your exact use, but I would the constantly function.

(run-jetty (constantly (response "hello")) 6789)

If you're trying to delay the computation with an anonymous function then this won't work (hint: use delay and force in that case), but for ring handlers it will work nicely.

Upvotes: 3

Related Questions