您正在使用函數pop
,它對不同的數據結構具有不同的行爲。
user> (pop '(0 1 2 3 4))
(1 2 3 4)
user> (pop [0 1 2 3 4])
[0 1 2 3]
user> (pop (map identity '(0 1 2 3 4)))
ClassCastException clojure.lang.LazySeq cannot be cast to clojure.lang.IPersistentStack clojure.lang.RT.pop (RT.java:640)
此外,你混合調用pop
通過調用first
。如果重複,則使用peek
/pop
或first
/rest
作爲成對,混合兩者可能會導致意外的結果。 first
/rest
是最低公分母,如果你想泛化各種順序類型,使用這些類型,並且他們會強制順序工作,如果可以的話。
user> (first "hello")
\h
user> (first #{0 1 2 3 4})
0
user> (first {:a 0 :b 1 :c 2})
[:c 2]
隨着你的功能,具有rest
更換pop
,我們得到了預期的結果:
user> (defn sdsu-nth
[input-list n]
(loop [cnt n tmp-list input-list]
(if (zero? cnt)
(first tmp-list)
(recur (dec cnt) (rest tmp-list)))))
#'user/sdsu-nth
user> (sdsu-nth (map identity '(0 1 2 3 4)) 2)
2
user> (sdsu-nth [0 1 2 3 4] 2)
2
user> (sdsu-nth '(0 1 2 3 4) 2)
2
user> (sdsu-nth "" 2)
\2
當你說 「沒有遞歸」 你的意思是 「遞歸」?這就是循環/重複結構。 – 2014-09-10 15:34:32
我的意思是說,我們可能想要使用循環結構,但函數不應該明確地對自己進行調用。 – 2014-09-10 15:39:57
請注意,即使在'loop'中使用'recur',它也是模仿遞歸(儘管它會被編譯爲循環),所以將這種構造看作遞歸匿名函數更自然。 – Mark 2014-09-10 16:00:28