制作列表递归Clojure的当前函数

时间:2015-10-30 12:16:43

标签: recursion clojure

您好我正在寻找一些Clojure代码的帮助。我写了一个函数,它将列入一个列表并计算列表的qty *价格,例如。 '(pid3 6 9)

我正在寻找的是扩展我当前的功能,以便递归地进行数量*价格计算,直到它到达列表的末尾。

我当前的功能是这样写的:

(defn pid-calc [list] (* (nth list 1) (nth list 2)))

我已尝试将其实现为递归函数,但根本没有运气,我希望能够调用这样的东西:

(pid-calcc '( (pid1 8 5) (pid2 5 6))
 return==> 70

我尽可能接近答案但似乎找不到答案。如果有人能帮助我找到一个解决方案我会很棒。到目前为止,我还没有找到任何可以编译的内容。

​(defn pid-calc [list]
   (if(empty? list)
    nil
    (* (nth list 1) (nth list 2)(+(pid-calc (rest list))))))

3 个答案:

答案 0 :(得分:2)

您不需要递归功能。只需使用+map

(defn pid-calc [list]
  (letfn [(mul [[_ a b]] (* a b))]
    (apply + (map mul list))))

答案 1 :(得分:1)

经过适当纠正的

@sloth's answer是解决问题的简洁快捷的方法。它向你展示了很多。

您尝试递归解决方案可以(a)修复

(defn pid-calc [list]
   (if (empty? list)
    0
    (let [x (first list)]
      (+ (* (nth x 1) (nth x 2)) (pid-calc (next list))))))

这适用于该示例,但是 - 正确递归 - 将在足够长的列表上耗尽堆栈空间。限制通常约为10K项。

我们可以克服这个问题而不像@sloth那样简洁。您可能会发现以下内容更容易理解:

(defn pid-calc [list]
  (let [line-total (fn [item] (* (nth item 1) (nth item 2)))]
    (apply + (map line-total list))))

答案 2 :(得分:0)

reduce非常符合您的情况:

(def your-list [[:x 1 2] [:x 1 3]])

(reduce #(+ %1 (* (nth %2 1) (nth %2 2))) 0 your-list)

(reduce #(+ %1 (let [[_ a b] %2] (* a b)) 0 your-list)