1.3.0 permalink Arrow_down_16x16

partial

clojure.core

  • (partial f arg1)
  • (partial f arg1 arg2)
  • (partial f arg1 arg2 arg3)
  • (partial f arg1 arg2 arg3 & more)
Takes a function f and fewer than the normal arguments to f, and
returns a fn that takes a variable number of additional args. When
called, the returned function calls f with args + additional args.

4 Examples top

  • user=> (def to-english (partial clojure.pprint/cl-format nil "~@(~@[~R~]~^ ~A.~)"))
    #'user/to-english
    
    user=> (to-english 1234567890)
    "One billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninety"
    
  • user=> (def hundred-times (partial * 100))
    #'user/hundred-times
    
    user=> (hundred-times 5)
    500
    
    user=> (hundred-times 4 5 6)
    12000
    
    user=> (def add-hundred (partial + 100))
    #'user/add-hundred
    
    user=> (add-hundred 5)
    105
    
  • (def subtract-from-hundred (partial - 100))
    
    user=> (subtract-from-hundred 10)      ; same as (- 100 10)
    90
    
    user=> (subtract-from-hundred 10 20)   ; same as (- 100 10 20)
    70
  • ; Maps exponent to coefficient
    ; x^3 + 2x + 1
    (def poly (fn [n]
    			(cond
    				(= 0 n) 1
    				(= 1 n) 2
    				(= 3 n) 1
    				:else 0)
    			)
    )
    
    ; Differentiates input by returning a polynomial that is curried
    ; 3x^2 + 2
    (defn diff [p]
    		(partial (fn [p n] (* (+ 1 n) (p (+ 1 n)))) p)
    	)
    
    (poly 3)
    ;=> 1
    ((diff poly) 3)
    ;=> 0
    ((diff poly) 2)
    ;=> 3
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2334 top

(defn partial
  "Takes a function f and fewer than the normal arguments to f, and
  returns a fn that takes a variable number of additional args. When
  called, the returned function calls f with args + additional args."
  {:added "1.0"
   :static true}
  ([f arg1]
   (fn [& args] (apply f arg1 args)))
  ([f arg1 arg2]
   (fn [& args] (apply f arg1 arg2 args)))
  ([f arg1 arg2 arg3]
   (fn [& args] (apply f arg1 arg2 arg3 args)))
  ([f arg1 arg2 arg3 & more]
   (fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))
Vars in clojure.core/partial:
Used in 0 other vars

Comments top

1 comment(s) for partial.

This function implements the concept of “currying”.

Log in to add a comment.