0

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
  • 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. Commented Mar 27, 2013 at 2:31

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But now I must use the keyword in the function call, don't I? (exp 2) doesn't seem to work.
Thats why I said "something similar" ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.