1
votes

I have a vector and want to call a function in Clojure. The function accepts many arguments and I have vector.

For example:

 (defn f [a b] (+ a b))

and I have the vector:

  [1 2]

I can use apply:

  (apply f [1 2])

But can I call f in Clojure like in python?

  (f *[1 2]) .

My use case is that I need to dissoc some keys from a map. I want to call (dissoc amap *keys), but it's not supported.

I could use apply

(apply dissoc (cons amap keys))

but it's not so convenient.

What's the best way to do this in Clojure?

1
What’s wrong with apply?Andrew Marshall
@user2219372 you could always build a macro that can read * and ** correctly but you should probably just let go with these python syntax details and dive into learning the clojure way!leontalbot
Perhaps it would help if you stated the benefits / difference you see in the python * operator over apply ?NielsK
I need to dissoc some keys from a map. I want to call (dissoc amap *keys),it's not supported. how to use apply? (apply dissoc (cons amap keys)). It's not convenient.user2219372
ok~,thank you very muchuser2219372

1 Answers

6
votes

As everyone else noticed, apply is the exact equivalent of Python's arbitrary argument lists. In your use-case, given

(def a-map {1 2, 3 4, 5 6})
(def some-keys (range 5))

to dissoc some-keys from a-map

(apply dissoc a-map some-keys)
; {5 6}

My original solution also works

(reduce dissoc a-map some-keys)
; {5 6}

but only because dissoc can take its key arguments one at a time or all at once.