递归可变参数 clojure 函数(unboxing/destructuring 调用函数时的列表)
Recursive variadic clojure function (unboxing/destructuring a list when calling a function)
只是想写一个递归可变参数函数来打印列表的元素,每次调用一个。第一次尝试:
(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)
然后,非常"un-elegant"的方式解决了:
(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
因为 tail
被解构为一个序列,并且您的函数是可变的,您需要 apply
tail
到您的函数,以便它在 [= 中的每个项目接收一个参数11=]:
(defn f1 [head & tail]
(println head)
(when tail (apply f1 tail)))
(f1 "one" "two" "three" "four")
;; one
;; two
;; three
;; four
只是想写一个递归可变参数函数来打印列表的元素,每次调用一个。第一次尝试:
(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)
然后,非常"un-elegant"的方式解决了:
(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
因为 tail
被解构为一个序列,并且您的函数是可变的,您需要 apply
tail
到您的函数,以便它在 [= 中的每个项目接收一个参数11=]:
(defn f1 [head & tail]
(println head)
(when tail (apply f1 tail)))
(f1 "one" "two" "three" "four")
;; one
;; two
;; three
;; four