0
votes

I'm a Python programmer just learning Clojure. In Python I love how I can used named arguments in a call to functools.partial:

def pow(base, exponent):
    return base ** exponent

exp = partial(pow, 2.71828)           # exp(2) --> 7.3886
square = partial(pow, exponent=2)     # square(2) --> 4

The implementation of exp is is obviously equivalent in Clojure - but could I use partial to define square succinctly, too? Is there a way to pass in keyword/named arguments to partial so that a specific argument is pre-determined? Or would this have to be handled not by partial but a function literal, e.g. #(pow % 2)?

1
Short answer: This isn't idiomatic. Clojure's preference for dispatch by argument count is related to what the JVM can implement efficiently (destructuring is considerably more expensive in comparison); the further you get from that, the more your code suffers.Charles Duffy

1 Answers

1
votes

For existing functions you will need to use function literal because they are not using keyword based arguments and use positional arguments.

For your own function you can do something similar:

(defn my-pow [& {:keys [base exponent]}]
  (Math/pow base exponent))

(def exp (partial my-pow :base 2.71828))
(exp :exponent 2)
(def square (partial my-pow :exponent 2))
(square :base 2)