Search code examples
clojure

Clojure - Too many arguments for function called with apply


I'm currently doing the tutorial examples for clojure, and one of them involves calling a function 3 times on multiple arguments, my code looks like this:

(defn triplicate [f] (dotimes [n 3] (f)))

(defn triplicate2 [f & args] (
   (triplicate #(apply f args))))

(triplicate2 #(println %) 1)

it works with 1 functiona and 1 rest parameter, but when I call it like this:

(triplicate2 #(println %) 1 3 4)

I get this error

ArityException Wrong number of args (2) passed to: 
user/eval1198/fn--1199  
clojure.lang.AFn.throwArity (AFn.java:429)

Am I thinking diferently from what I should?

Help !


Solution

  • The function you are passing to triplicate2

    #(println %)
    

    is expecting one argument and you are passing one in the working example and three in the non-working example.

    Since println is already variadic, you can just call

    (triplicate2 println 1)
    

    and

    (triplicate2 println 1 3 4)