我是clojure的新手(和该函数的程序设计),我正在尝试做一些基本的问题。我试图在没有递归的序列中找到第n个元素。
所以像
(my-nth '(1 2 3 4) 2) => 3
我很难遍历列表并在找到第n个元素时返回。我尝试了多种方法,最终得到的代码是
(defn sdsu-nth
[input-list n]
(loop [cnt n tmp-list input-list]
(if (zero? cnt)
(first tmp-list)
(recur (dec cnt) (pop tmp-list)))))
这给了我一个例外,上面写着“无法从空列表弹出”
我不需要代码,但是如果有人可以指出正确的方向,那将真的很有帮助!
您正在使用函数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]
使用您的函数替换pop
为rest
,我们将获得预期的结果:
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 "01234" 2)
\2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句