You're viewing version 1.2.0 of fn. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16
  • (fn & sigs)
(fn name? [params* ] exprs*)
(fn name? ([params* ] exprs*)+)

params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol

Defines a function

2 Examples top

  • ;; simple anonymous function passed to (map )
    user=> (map (fn [x] (* x x)) (range 1 10))
    (1 4 9 16 25 36 49 64 81) 
    ;; anonymous function with a name.  not so anonymous now is it?
    ;; this is useful in stack traces
    (fn add [a b] (+ a b))
    ;; anonymous function with two params, the second is destructured
    user=> (reduce (fn [m [k v]] (assoc m v k)) {} {:b 2 :a 1 :c 3})
    {2 :b, 1 :a, 3 :c} 
    ;; define and instantly call an anonymous function
    user=> ((fn [a b c] (+ a b c)) 2 4 6)
    ;; define and instantly call an anonymous variadic function 
    ;; "nums" is a list here
    user=> ((fn [& nums] (/ (apply + nums) (count nums))) 1 2 3 4)
    ;; define and instantly call an anonymous mixed function
    ;; "nums" is a list, while "int" is a number
    user=> ((fn [int & nums] (+ int (/ (apply + nums) (count nums)))) 10 1 2 3 4)
    ;; define and instantly call an anonymous overloaded function 
    ;; even though it is quite pointless
    user=>  ((fn ([a] (inc a)) ([a b] (+ a b))) 3)
  • ;; the shortcut form for (fn ) is #( )
    ;; where parameters are referred by their index with the prefix %
    ;; the equivalent of 
    user=> ((fn [a b c] (+ a b c)) 2 4 6)
    ;; is
    user=> (#(+ %1 %2 %3) 2 4 6)
Log in to add / edit an example.

See Also top

  • 0

    Same as (def name (fn [params* ] exprs*)) or (def name (fn ([para

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:3491 top

(defmacro fn
  "(fn name? [params* ] exprs*)
  (fn name? ([params* ] exprs*)+)

  params => positional-params* , or positional-params* & next-param
  positional-param => binding-form
  next-param => binding-form
  name => symbol

  Defines a function"
  {:added "1.0"}
  [& sigs]
    (let [name (if (symbol? (first sigs)) (first sigs) nil)
          sigs (if name (next sigs) sigs)
          sigs (if (vector? (first sigs)) (list sigs) sigs)
          psig (fn* [sig]
                 (let [[params & body] sig
                       conds (when (and (next body) (map? (first body))) 
                                           (first body))
                       body (if conds (next body) body)
                       conds (or conds (meta params))
                       pre (:pre conds)
                       post (:post conds)                       
                       body (if post
                              `((let [~'% ~(if (< 1 (count body)) 
                                            `(do ~@body) 
                                            (first body))]
                                 ~@(map (fn* [c] `(assert ~c)) post)
                       body (if pre
                              (concat (map (fn* [c] `(assert ~c)) pre) 
                   (maybe-destructured params body)))
          new-sigs (map psig sigs)]
        (if name
          (list* 'fn* name new-sigs)
          (cons 'fn* new-sigs))
        (meta &form))))
Vars in clojure.core/fn: cons defmacro let list* meta name with-meta
Used in 386 other vars (expand)
instance? bound-fn add-watch string? second letfn ns-publics sync complement defmethod ns-interns next import last with-meta butlast seq? with-loading-context future char? conj assoc doto vector? ns-refers proxy-super memfn frequencies definline bound-fn* seq pvalues re-seq print-dup nnext ffirst drop-last replace defn map? file-seq with-bindings comp constantly sort-by reduce str first bean memoize defmacro fnext group-by print-method fnil partial comparator proxy rest nfirst juxt meta get-child formatter-out formatter apropos rename-keys select join intersection map-invert difference index do-template deftest- deftest use-fixtures test-all-vars compose-fixtures assert-expr set-test with-test tap-report prewalk-demo postwalk-demo keywordize-keys stringify-keys postwalk-replace macroexpand-all prewalk-replace vector-zip seq-zip xml-zip add maximum empty-maximum minimum empty-minimum combine deftype min-max capture-and-send imaginary complex handler-case add-cell-watcher eval-cell ensure-relation merge-indexes apply-rules-set reverse-map literal-appropriate? join-literal adorned-literal build-partial-tuple copy throw-msg rebind-fn in-case-test apropos find-javadoc-url conj assoc into get dissoc fmap add-loops remove-loops transitive-closure headers send-request-entity copy with-system-properties as-str tabular-data->map as-str jmx->clj composite-data->map map->attribute-infos mbean formatter-out fibs fill-queue log deep-merge-with expt make-arg-checker make-count-checker read-line read-char print state-m-until write skip-chars println flush m-seq m-fmap call-cc m-chain set-val update-state with-state-field set-state m-lift update-val formatter execute-format emit-nl? compile-format random-stream normal-box-muller normal reject lcg summarize with-system-properties frequencies rotations group-by includes? fill-queue frequencies rotations group-by includes? global-singleton per-thread-singleton with-query-results transaction with-connection rollback re-partition re-gsub replace partial grep blank? partition replace-first pick st-as-stream stream-map stream-filter grep blank? partition add-menu-item do-swing do-swing-and-wait deftest- do-template deftest use-fixtures flatten-map test-all-vars compose-fixtures assert-expr set-test with-test dotrace deftrace with-ns mapcat-chain attr seq-test tag= text= attr= make-service-method wrap-cookies wrap-file wrap-file-info wrap-flash wrap-keyword-params wrap-lint parse-multipart-params wrap-multipart-params wrap-params wrap-reload wrap-session wrap-stacktrace wrap-static bind-columns plus minus div kronecker mult mmult pow save view add-subtitle conj-cols set-theme-default add-lines* set-data set-theme-bw sliders set-background-default query-to-pred conj-rows atan2 sel $fn bind-rows matrix-map $map read-xls hessian gradient text-width lee-distance cdf-empirical pairs minkowski-distance chebyshev-distance deriv-fn* deftarget define-all-ant-tasks coerce stale-namespaces defproject copy-dependencies copy-to-jar form-for-testing-namespaces for-these make-arg-checker make-count-checker for-these choose-from symbol-of unicode printable-ascii-string string-of printable-ascii list-of unicode-string run-test rewrite-=> should-body local-bindings given and when then java-props->sh-args local-bindings union do-> get-resource transform-content snippet* defsnippets intersection transformation clone-for at* let-select move lockstep-transformation swank-toggle-trace unmunge dothread-keeping one-of? local-bindings keep-bindings dothread path-class-files with-timeout fuzzy-completions inspect-meta-information ns-refers-by-ns inspector-call-nth-action emacs-inspect label-value-line* print-object dispatch-message register-dispatch start-repl start-server exactly in-any-order exactly call-being-tested arg-matcher-maker fake in-any-order exactly arg-matcher-maker in-any-order keychain-passphrase memfn-varargs contract new-object-tester partial-namespace-matcher combine-matchers new-sandbox new-sandbox-compiler dot-maker namespace-matcher tree-map class-matcher add-reader-to-sandbox new-tester function-matcher fn-seq button-group auto-setters icon-setters group-container-args seq-ref-combobox-model shelf mapref-tree-model general-panel stack seq-ref-list-model frame expect make-arg-checker make-count-checker subsets funcify* provide-contracts

Comments top

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