Clojure 实践:交错 - outOfmemoryError
Clojure Practice : Interleave - outOfmemoryError
我正在尝试为自己实现 'interleave',但遇到了 outOfMemoryError
我的版本应该是一样的:
(interleave [1 2] [3 4])
代码如下:
(defn myInterleav [col1 col2]
(loop [r []
c1 (first col1)
c2 (first col2)]
(if (and c1 c2)
(recur (conj (conj r c1) c2)
(next col1)
(next col2))
r)))
(myInterleav [1 2] [3 4])
版本 2 'noisesmith' 建议重新绑定 args,但出现空指针错误。
(defn myIL2 [col1 col2]
(loop [m []
[e1 & c1] col1
[e2 & c2] col2]
(if (and e1 e2)
(recur (conj m e1 e2)
c1
c2)
m
)))
如果两个输入都不为空,您的函数永远不会 returns,因为 col1
和 col2
的绑定无法更改。您需要重新设计循环以每次重新绑定到前一个绑定的 next
,而不是初始函数输入的 next
。这样的事情应该有效:
[...
[e1 & c1] col1
[e2 & c2] col2]
(if (and (seq col1) (seq col2))
(recur (conj r e1 e2)
c1
c2)
...)
我正在尝试为自己实现 'interleave',但遇到了 outOfMemoryError
我的版本应该是一样的:
(interleave [1 2] [3 4])
代码如下:
(defn myInterleav [col1 col2]
(loop [r []
c1 (first col1)
c2 (first col2)]
(if (and c1 c2)
(recur (conj (conj r c1) c2)
(next col1)
(next col2))
r)))
(myInterleav [1 2] [3 4])
版本 2 'noisesmith' 建议重新绑定 args,但出现空指针错误。
(defn myIL2 [col1 col2]
(loop [m []
[e1 & c1] col1
[e2 & c2] col2]
(if (and e1 e2)
(recur (conj m e1 e2)
c1
c2)
m
)))
如果两个输入都不为空,您的函数永远不会 returns,因为 col1
和 col2
的绑定无法更改。您需要重新设计循环以每次重新绑定到前一个绑定的 next
,而不是初始函数输入的 next
。这样的事情应该有效:
[...
[e1 & c1] col1
[e2 & c2] col2]
(if (and (seq col1) (seq col2))
(recur (conj r e1 e2)
c1
c2)
...)