我在Clojure Quil库中找出算法存在严重问题。我一直试图用功能中间件模式制作一些网络/植绒模式的图表,如this。我的问题是你如何在Quild中创建一个嵌套的“for循环”,以便将任何给定点连接到任何其他带有线的点?区别在于连接1-> 2 3-> 4 ...等的一组点和连接的组1-> 2 1-> 3 1-> 4 2-> 3 2 - →4 ...等
我的程序看起来像这样,虽然为了这个问题,我试图将它编辑为通用的。
(ns stack-question.core
(:require [quil.core :as q]
[quil.middleware :as m]))
;how to draw the point
(defn draw-points [point]
(q/point (:x point) (:y point)))
;the main data structure
(defn make-point [num]
{:name num
:x (rand 500.0)
:y (rand 500.0)})
;draws connections between two objects
(defn connections [p1 p2]
(q/stroke 200 200 100 150)
(q/line (:x p1) (:y p1) (:x p2) (:y p2)))))
(defn setup []
(q/frame-rate 30)
{:points (map make-points (take 1000 (range)))})
;this function isn't important to the question
;but let's just say that the points move position each frame
(defn update-state [state]
(update state :points move-group))
;this is the problem function here.
;I'm trying to map over the collection, but with a fixed head
;and do so for each element in the collection
(defn make-conts [coll]
(loop [x coll]
(when (not (empty? (rest coll)))
(map (partial connections (first x)) (rest x))
(recur (rest x)))))
(defn draw-state [state]
(do
;(q/frame-rate 1)
(q/background 0)
(doseq [x (map draw-point (:points state))] x)
(doseq [x (make-conts (:points state))] x)))
(q/defsketch stack-question
:title "GL"
:size [500 500]
:setup setup
:update update-state
:draw draw-state
:middleware [m/fun-mode]
:renderer :opengl)
我希望这不是完全不透明的。
答案 0 :(得分:1)
您的代码存在两个问题:
首先,您要在(rest coll)
语句中检查(rest x)
而不是when
,从而导致无限循环。
第二个是map
返回一个懒惰序列,这意味着对connections
的调用没有发生。这可以通过使用map
将调用包装到doall
来修复,但由于您对副作用感兴趣而不是返回值,因此您应该使用doseq
。
此版本的功能(多余的loop
也已删除)应该有效:
(defn make-conts [coll]
(when (not (empty? (rest coll)))
(doseq [endpoint (rest coll)]
(connections (first coll) endpoint))
(recur (rest coll))))
您可以使用combinations
中的clojure.math.combinatorics
代替编写代码以自行生成组合:
(require '[clojure.math.combinatorics :as combi])
(defn make-conts [coll]
(doseq [[p1 p2] (combi/combinations coll 2)]
(connections p1 p2)))