【发布时间】:2018-03-30 15:32:25
【问题描述】:
只是想写一个递归可变参数函数来打印列表的元素,每次调用一个。第一次尝试:
(defn f1 [head & tail]
(when-not (nil? head)
(println head )
(f1 tail) ;; how to unbox/destructure tail ????
) ;; when
) ;; defn
(f1 "one" "two" "three" "four")
但只要得到:-(
one
(two three four)
然后,以一种非常“不优雅”的方式解决它:
(defn f2Aux [all]
(when-not (empty? all)
(println (first all) )
(f2Aux (rest all))
)
) ; defn
(defn f2 [head & tail]
(f2Aux (list* head tail))
) ;; defn
(f2 "one" "two" "three" "four")
很确定有更好的方法。
谢谢
编辑。仍在寻找与以下不同的东西:
(defn f3
;; if we get a list
([all]
(when-not (empty? all)
(println (first all) )
(f3 (rest all))
) ; when
)
;; if we get several args
([head & tail]
(f3 (list* head tail)) ;; pack the args and call us again
)
) ;; defn
【问题讨论】:
标签: clojure variadic-functions destructuring