How to make a Clojure function take a variable number of parameters?

后端 未结 5 1607
闹比i
闹比i 2020-12-08 05:57

I\'m learning Clojure and I\'m trying to define a function that take a variable number of parameters (a variadic function) and sum them up (yep, just like the + pro

相关标签:
5条回答
  • 2020-12-08 06:24

    defn is a macro that makes defining functions a little simpler. Clojure supports arity overloading in a single function object, self-reference, and variable-arity functions using &

    From http://clojure.org/functional_programming

    0 讨论(0)
  • 2020-12-08 06:25
    (defn sum [& args]
      (print "sum of" args ":" (apply + args)))
    

    This takes any number of arguments and add them up.

    0 讨论(0)
  • 2020-12-08 06:29

    In general, non-commutative case you can use apply:

    (defn sum [& args] (apply + args))
    

    Since addition is commutative, something like this should work too:

    (defn sum [& args] (reduce + args))
    

    & causes args to be bound to the remainder of the argument list (in this case the whole list, as there's nothing to the left of &).

    Obviously defining sum like that doesn't make sense, since instead of:

    (sum a b c d e ...)
    

    you can just write:

    (+ a b c d e ....)
    
    0 讨论(0)
  • 2020-12-08 06:29

    Yehoanathan mentions arity overloading but does not provide a direct example. Here's what he's talking about:

    (defn special-sum
      ([] (+ 10 10))
      ([x] (+ 10 x))
      ([x y] (+ x y)))
    

    (special-sum) => 20

    (special-sum 50) => 60

    (special-sum 50 25) => 75

    0 讨论(0)
  • 2020-12-08 06:31
     (defn my-sum
      ([]  0)                         ; no parameter
      ([x] x)                         ; one parameter
      ([x y] (+ x y))                 ; two parameters
      ([x y & more]                   ; more than two parameters
    
    
        (reduce + (my-sum x y) more))
      )
    
    0 讨论(0)
提交回复
热议问题