Clojure堆栈溢出使用递归,懒惰序列?

| 我已经读过其他人有关Clojure中出现堆栈溢出问题的问题,该问题往往是某个地方建立的惰性序列。这似乎是这里的问题,但是对于我一生来说,我不知道在哪里。 这是代码,代码后面有一点解释:
(defn pare-all []
  \"writes to disk, return new counts map\"
(loop [counts (counted-origlabels)
     songindex 0]
(let [[o g] (orig-gen-pair songindex)]
  (if (< songindex *song-count*) ;if we are not done processing list
    (if-not (seq o) ;if there are no original labels
      (do
        (write-newlabels songindex g);then use the generated ones
        (recur counts (inc songindex)))
      (let [{labels :labels new-counts :countmap} (pare-keywords o g counts)] ;else pare the pairs
        (write-newlabels songindex labels)
        (recur new-counts (inc songindex))))
    counts))))
有一个映射存储在\“ counts \”中,该映射最初是从\“ counted-origlabels \”函数中获取的。该映射具有字符串键和整数值。它的长度为600左右,并且在迭代过程中会更新值,但长度保持不变,我已经对此进行了验证。 \“ orig-gen-pair \”函数从文件中读取并返回简短的序列对,每个序列约10个左右。 \“ write-newlabels \”函数只是将传递的序列写到磁盘上,没有任何其他副作用,也不返回值。 \“ Pare-keywords \”返回一个简短的序列和\“ counts \”映射的更新版本。 我只是看不到什么延迟序列可能导致这里的问题! 任何提示将不胜感激! - - 编辑 - - 大家好,我已经更新了我的功能,希望是更加惯用的Clojure。但是我原来的问题仍然存在。首先,这是新代码:
(defn process-song [counts songindex]
  (let [[o g] (orig-gen-pair songindex)]
(if-not (seq o) ;;if no original labels
  (do
    (write-newlabels songindex g);then use the generated ones
    counts)
  (let [{labels :labels new-counts :countmap} (pare-keywords o g counts)] ;else pare the pairs
    (write-newlabels songindex labels)
    new-counts))))

(defn pare-all []
  (reduce process-song (counted-origlabels) (range *song-count*)))
这仍然以java.lang.StackOverflowError(repl-1:331)结尾。堆栈跟踪对我来说并没有多大意义,只不过它似乎表明延迟序列混乱正在继续。还有更多提示吗?我需要将代码发布到过程歌曲调用的函数中吗?谢谢!     
已邀请:
如果没有更多具体的示例数据,我无法完全理解您要做什么,但是很明显,您正在尝试使用递归来迭代数据。您正在使事情变得比自己更痛苦。 如果您可以生成一个函数,将其称为“做事”,并且该函数可以在地图中的单个条目上正常运行,那么您可以调用(“地图做事”(counted-origlabels)),然后将对(counting-origlabels)中的每个映射条目应用(do-the-thing),将单个映射条目作为唯一参数传递给do-thething,并从do-the返回一系列返回值-事情。 您看起来还需要索引,这也很容易解决。您可以将惰性序列(范围)作为第二个参数进行拼接,然后您将在每个映射条目中生成一系列索引。但是,clojure中的映射默认情况下不会进行排序,因此,除非您使用的是排序映射,否则此索引值相对没有意义。 尝试抽象化您到目前为止编写的内容,尝试执行以下操作:
(defn do-the-thing [entry index counts]
  (let [[o g] (orig-gen-pair index)]
    (if-not (seq o)
      (write-newlabels index g)
      (let [{labels :labels new-counts :countmap} (pare-keywords o g counts)]
        (write-newlabels index labels)))))

(map do-the-thing (counted-origlabels) (range) (constantly (counted-origlabels)))
    

要回复问题请先登录注册