0

I'm writing some code using Reagent, and part of that involves writing some callbacks and state manipulation.

A few of those places will invoke functions with default arguments, and I don't want to do anything with them. I just want to return a constant value.

When I use something like #(true), for instance, I'll get an exception, and I have to write (fn [_] true). Is there a way for the lambda shorthand to know it's getting a parameter and not using it?

Brandon Olivier
  • 578
  • 5
  • 16
  • 1
    Possible duplicate of [Declare dummy (unused) parameters for Clojure anonymous function](http://stackoverflow.com/questions/41909132/declare-dummy-unused-parameters-for-clojure-anonymous-function) – Sylwester Mar 16 '17 at 11:12

1 Answers1

1
#(do % true)

But honestly, I just write the full version without the macro. It makes it much clearer what the intent is.

It's a shame Clojure doesn't seem to have a version of Haskell's const function. It takes a value and returns a function that throws away its argument and returns the value. Very handy for situations like this. It's trivial to write your own version for your library however:

(defn const [value]
    (fn [_] value))

(some-hof (const true))

With some creativity, it probably wouldn't be difficult to make const support any number of arguments.


Edit:

@amalloy pointed out that Clojure does in fact have such a function! core/constantly.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117