You're viewing version 1.2.0 of apply. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

apply

clojure.core

  • (apply f args* argseq)
Applies fn f to the argument list formed by prepending args to argseq.

6 Examples top

  • user=> (def *strings* ["str1" "str2" "str3"])
    #'user/*strings*
    
    ;; Oops!
    user=> (str *strings*)
    "[\"str1\" \"str2\" \"str3\"]"
    
    ;; Yay!
    user=> (apply str *strings*)
    "str1str2str3"
    user=>
    
    ;; Note the equivalence of the following two forms
    user=> (apply str ["str1" "str2" "str3"])
    "str1str2str3"
    
    user=> (str "str1" "str2" "str3")
    "str1str2str3"
    
  • ;; If you were to try
    user=> (max [1 2 3])
    [1 2 3]
    
    ;; You would get '[1 2 3]' for the result. In this case, 'max' has received one
    ;; vector argument, and the largest of its arguments is that single vector.
    
    ;; If you would like to find the largest item **within** the vector, you would need
    ;; to use `apply`
    
    user=> (apply max [1 2 3])
    3
    
    ;; which is the same as (max 1 2 3)
    
  • ;; Here's an example that uses the optional second argument, args:
    
    user=> (apply map vector [[:a :b] [:c :d]])
    ([:a :c] [:b :d])
    
    ;; In this example, 'f' = 'map', 'args' = 'vector', and argseq = '[:a :b] [:c :d]',
    ;; making the above code equivalent to
    
    user=> (map vector [:a :b] [:c :d])
    ([:a :c] [:b :d]) ;Same answer as above
    
    ;; It might help to think of 'map' and 'vector' "slipping inside" the argument list
    ;; ( '[[:a :b] [:c :d]]' ) to give '[map vector [:a :b] [:c :d]]' , which then 
    ;; becomes the executable form '(map vector [:a :b] [:c :d])' .
  • ;; only functions can be used with apply.  'and' is a macro
    ;; because it needs to evaluate its arguments lazily and so
    ;; does not work with apply.
    user=> (apply and (list true true false true)
    
    -> ERROR
    
    
  • ;apply is used to apply an operator to its operands. 
    
    (apply + '(1 2))  ; equal to (+ 1 2)
    => 3
    
    
    ;you can also put operands before the list of operands and they'll be consumed in the list of operands
    
    (apply + 1 2 '(3 4))  ; equal to (apply + '(1 2 3 4))
    => 10
  • ;; You can use map and apply together to drill one level deep in a collection
    ;; of collections, in this case returning a collection of the max of each
    ;; nested collection
    
    user=> (map #(apply max %) [[1 2 3][4 5 6][7 8 9]])
    (3 6 9)
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:535 top

(defn apply
  "Applies fn f to the argument list formed by prepending args to argseq."
  {:arglists '([f args* argseq])
   :added "1.0"}
  ([^clojure.lang.IFn f args]
     (. f (applyTo (seq args))))
  ([^clojure.lang.IFn f x args]
     (. f (applyTo (list* x args))))
  ([^clojure.lang.IFn f x y args]
     (. f (applyTo (list* x y args))))
  ([^clojure.lang.IFn f x y z args]
     (. f (applyTo (list* x y z args))))
  ([^clojure.lang.IFn f a b c d & args]
     (. f (applyTo (cons a (cons b (cons c (cons d (spread args)))))))))
Vars in clojure.core/apply: cons defn list* seq
Used in 374 other vars (expand)
time not= for sync complement dotimes with-in-str defrecord prn with-out-str print vary-meta with-loading-context future update-in with-bindings* doto print-str proxy-super map memfn prn-str when-first mapcat definline bound-fn* aset with-precision proxy-name or condp with-local-vars with-bindings when-let comp pr-str interleave amap while case printf require deftype fnil partial pmap if-let and locking definterface delay defmulti proxy println aget pr defonce areduce use juxt trampoline println-str binding output-stream copy writer make-parents reader input-stream with-sh-dir with-sh-env with-bindings formatter-out formatter with-pprint-dispatch pprint-logical-block dir print-trace-element join deftest- assert-predicate testing-contexts-str deftest testing try-expr run-all-tests assert-any with-test-out set-test with-test test-name with-junit-output with-tap-output walk edit xml-zip maximum empty-maximum minimum empty-minimum deftype capture-and-send make-map join with-command-line print-help cond-let handler-case defalias defnk ?- <- get-all-relations database-merge add-tuples map-values preduce with-in-reader with-out-append-writer with-out-writer deferror throw-msg continue continue-with with-handler rebind-fn do-not-handle fnmap run* defadt greatest-by all-least-by all-least greatest least least-by all-greatest all-greatest-by with-in-reader with-out-append-writer with-out-writer with-system-properties with-connection formatter-out log spy with-logs lazy-get deep-merge-with times has-args expect with-monad monad monad-transformer formatter prerr pprint-condp with-pprint-dispatch pprint-logical-block prob with-profile-data prof with-system-properties print-repl-info stream-repl rec-seq rec-seq with-sh-dir with-sh-env with-sh-dir with-sh-env with-query-results transaction with-connection insert-values create-table insert-rows str-join re-gsub repeat map-str join docodepoints dochars partial defst repeat map-str docodepoints dochars do-swing do-swing-and-wait deftest- assert-predicate testing-contexts-str deftest testing try-expr run-all-tests assert-any with-test-out set-test with-test dotrace deftrace trace-indent match with-ns with-temp-ns xml1-> seq-test text executor-execute defservice kronecker time-series-plot box-plot add-box-plot add-categories $ stacked-bar-chart bar-chart heat-map xy-plot pie-chart scatter-plot dynamic-scatter-plot line-chart function-plot add-points histogram sliders add-function add-lines stacked-area-chart area-chart dynamic-xy-plot add-histogram sliders* defop combine-with $fn with-data transform-with matrix-map $map LINE with-rotation sketch with-translation sum-of-square-devs-from-mean lee-distance n-grams hamming-distance minkowski-distance sum-variance-test correlation-ratio chebyshev-distance deriv-fn deriv-fn* define-ant-task define-ant-type deftarget checkout-deps-paths eval-in-project compile defproject -main help-summary-for repl-server form-for-testing-namespaces testing-fn for-these it re-test defconfig expand-subcontext-forms defn! times has-args expect fail for-these string-of collection-generator for-all testing-fn it report-tally with-timing tally rewrite-=> debug-repl given and when then with-re-defn re-test add-class set-attr remove-attr transform-content snippet* text zip-select html-snippet defsnippets transformation clone-for sniptest* html-content let-select move has-class lockstep-transformation eval-from-control with-emacs-package cause-restart-for dothread-keeping-clj continuously dothread-keeping one-of? returning keep-bindings largest-common-prefix dothread dothread-swank with-package-tracking unacronym with-timeout fuzzy-completions run-hook with-connection inspector-call-nth-action with-swank-io dispatch-message log-event start-repl call-being-tested expect fake with-default-identity memfn-varargs with-connection with-default-session-options with-ssh-agent i-want new-sandbox-compiler add-reader-to-sandbox default-obj-tester secure-tester combine-testers extend-tester general-button add-action-listener kw-to-setter add-listener label shelf general-panel jlist stack frame list-model tree add-list-selection-listener expect has-args selections times contract with-constraints

Comments top

No comments for apply. Log in to add a comment.