代码之家  ›  专栏  ›  技术社区  ›  hawkeye

clojure中的合并cond参数(cl样式)

  •  2
  • hawkeye  · 技术社区  · 14 年前

    在Clojure我做这个

    (println (cond false "don't care" "otherwise" "otherwise"))
    

    在通常的Lisp中,这是

    (print (cond (nil "don't care") ("otherwise") ))
    

    cond 在克洛杰里?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Jake McCrary    14 年前

    my-cond cond :else

    (defmacro my-cond
      [& others]
      (if others
        (let [more# (next others)
              extra-clauses# (if more# `(my-cond ~@more#))
              clause# (first others)]
          (if (= 2 (count clause#))
            `(if ~(first clause#) ~(second clause#) ~extra-clauses#)
            `(if ~(first clause#) ~(first clause#)  ~extra-clauses#)))))
    
    
    (deftest my-cond-works
      (is (= 3 (my-cond (false 1) (false 2) (3))))
      (is (= "otherwise" (my-cond (false "don't care") ("otherwise"))))
      (is (= nil (my-cond (:one nil) ("otherwise"))))
      (is (= "care" (my-cond (1 "care") ("otherwise"))))
      (is (= "otherwise" (my-cond (false "care") ("otherwise") (true "true"))))
      (is (= "silly" (my-cond (nil "no") (nil) ("yes" "silly")))))
    

    (defmacro my-cond [[if1 then1] & others]
      (when (or if1 then1 others)
        (let [extra-clauses# (if others `(my-cond ~@others))]
          (if then1
            `(if ~if1 ~then1 ~extra-clauses#)
            `(if ~if1 ~if1  ~extra-clauses#)))))
    
    user> (my-cond (false "first") (nil nil) ("otherwise"))
    "otherwise"
    
        2
  •  0
  •   p-lo    14 年前

    (defmacro my-cond [[if1 then1] & others]
      (if others 
        `(if ~if1 ~then1 (my-cond ~@others))
        `(if ~if1 ~then1)))
    

    (my-cond (false 1) (false 2) (3 3))   ; results in 3