embee
embee

Reputation: 95

Partial and named arguments in Clojure

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)?

Upvotes: 0

Views: 673

Answers (1)

Ankur
Ankur

Reputation: 33637

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)

Upvotes: 1

Related Questions