【问题标题】:Recursive variadic clojure function (unboxing/destructuring a list when calling a function)递归可变参数 clojure 函数(在调用函数时拆箱/解构列表)
【发布时间】: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


    【解决方案1】:

    因为tail 被解构为一个序列,并且您的函数是可变参数,所以您需要将apply tail 传递给您的函数,以便它在tail 中的每个项目接收一个参数:

    (defn f1 [head & tail]
      (println head)
      (when tail (apply f1 tail)))
    
    (f1 "one" "two" "three" "four")
    ;; one
    ;; two
    ;; three
    ;; four
    

    【讨论】:

    • 好点!谢谢
    • 这里不需要seq 调用。 & tail 永远不会将 tali 绑定到空序列:它将是 nil 或非空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2023-04-03
    相关资源
    最近更新 更多