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

递归可变clojure函数(调用函数时取消装箱/解构列表)

  •  0
  • cibercitizen1  · 技术社区  · 7 年前

    只需编写一个递归变量函数,打印列表中的元素,每次调用一个。第一次尝试:

    (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
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Taylor Wood    7 年前

    因为 tail 被分解成一个序列,而你的函数是可变的,你需要 apply 使函数中的每个项都接收一个参数 :

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