recursion - 第 i 个和第 i+1 个元素循环的惯用 clojure

标签 recursion for-loop clojure lisp

我一直在思考如何实现 algorithm计算多边形相对于一个点的缠绕数。目前的实现如下:(注意更新所以代码有效)

(defn winding-num
  "Return winding number of polygon
  see Alciatore "
  [poly point]
        ; translate poly such that point is at origin
  (let [translated-poly (map #(vec-f - % point) poly)]
    ; w is wind-num
    (loop [vertices translated-poly w 0]
      (cond
        (= (count vertices) 1)
        w

        :else
        (let [x1 (first (first vertices))
              x2 (first (second vertices))
              y1 (second (first vertices))
              y2 (second (second vertices))]
          (cond 
            (and (< (* y1 y2) 0)
                 (> (+ x1 (/ (* y1 (- x2 x1))
                         (- y1 y2)))
                    0))
            (if (< y1 0)
                (recur (rest vertices) (inc w))
                (recur (rest vertices) (dec w)))

            (and (zero? y1)
                 (> x1 0))
            (if (> y2 0)
                (recur (rest vertices) (+ w 0.5))
                (recur (rest vertices) (- w 0.5)))

            (and (zero? y2)
                 (> x2 0))
            (if (< y1 0)
                 (recur (rest vertices) (+ w 0.5))
                 (recur (rest vertices) (- w 0.5)))

            :else
            (recur (rest vertices) w)))))))

我的问题是

  • 人们说,在可能的情况下,最好使用在比显式递归更高级别运行的循环结构;例如mapforreduce
  • rest 函数将向量转换为列表

我可以想到使用 for 和索引的实现,但我也听说最好不要使用索引。

是否有一种惯用的方法来处理在每次迭代中需要访问连续值的向量算法?

最佳答案

一般来说,如果你想访问一个序列的连续值,一次访问两个,你可以使用分区函数。分区允许您指定组大小和步长:

user> (partition 2 1 (range 10))
((0 1) (1 2) (2 3) (3 4) (4 5) (5 6) (6 7) (7 8) (8 9))

关于recursion - 第 i 个和第 i+1 个元素循环的惯用 clojure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16289090/

相关文章:

c++ - 给定中序和后序遍历,如何输出树的前序遍历?

c++ - 我的 for 循环怎么搞砸了?

clojure - 在 clojure 中向字符串添加变量

haskell - 什么是隐式递归?

recursion - 递归计算k-ary树中的节点

c++ - 如何删除字符串中的字符?

c - 为什么 return 在此代码中不起作用?

maven - 自动化 Leiningen 本地依赖管理

optimization - Clojure 中的快速复数运算

r - 在 R 中建立家庭嵌套树父/子关系