An idiomatic way to pass the name of a method to evaluate in Clojure?

I am passing the name of the function to use in another method.

(defn mapper [m function]
  (cond
   (= '() m) '()
   true (cons (function (first m))
            (mapper (rest m) function))))

(println (mapper '((blue red)(green red)(white red)) #'first))

Is there a more idiomatic way to do this in clojure?

+5
source share
3 answers
  • Preferred vectors to lists. You should not quote a vector most of the time, and it has better performance for many things, such as random access. Lists are used much less frequently in Clojure than in other Lisps.
  • . " " . Clojure , . , , . Clojure, .
  • #'first - var, ""; first - var, "", .. fn. (#'first foo) (first foo) , #'first , . , , . #'.
  • map , - . map , . chunked seqs, , . .
  • (= '() x), seq (seq x), nil, x . , Clojure, (= '() nil) .
  • - ( ), . ().
  • map , . , . , : "(map f coll): ".
  • cond, . if. if nil, when. when if, , , cond - .

Rafał Dowgird , , . :

user> (mapper first [[:blue :red] [:green :red] [:white :red]])
(:blue :green :white)
+8

, . Clojure map :

(defn mapper [coll f]
 (when-let [s (seq coll)]
    (cons (f (first s)) (mapper (rest s) f))))

- , , chunked-seqs .. , , , .

coll f , .

+4

. , clojure, "coll" . "", , -, . Clojure .

: .

  • : else 'cond' escape Common Lisp style 'T'.
  • , , .

, :

user> (defn mapper [coll f]
        (cond
          (not (seq coll)) nil
          :else (conj (mapper (next coll) f)
                      (f (first coll)))))
#'user/mapper
user> (mapper '(1 2 3) #(* % %))
(1 4 9)
user> (mapper [1 2 3] #(* % %))
(1 4 9)

, conj " " . , . "next" lisp. "next" . , seq'ing , nil . , .

+4

All Articles