第 21 个 4clojure 问题要求您实现nth
.
但是我尝试实现它:
(defn my-nth
([s 0] (first s))
([s n] (recur s (- n 1))))
导致错误“不支持的绑定形式:0”
有人可以解释为什么这是错误以及如何修复它吗?
在函数的参数中,不能指定值,只能指定符号。可能你从 Haskell 借用了那个语法,你可以在那里做到这一点。但不是在 Clojure 中。
在您的示例中,代码如下所示:
(defn nth-my [coll index not-found]
(if (zero? index)
(if (empty? coll)
not-found
(first coll))
(recur (rest coll) (dec index) not-found)))
用法:
user> (nth-my [1 2 3] 0 "dunno")
1
user> (nth-my [1 2 3] 1 "dunno")
2
user> (nth-my [1 2 3] 2 "dunno")
3
user> (nth-my [1 2 3] 4 "dunno")
dunno
欢迎您通过以下方式对其进行改进:
检查负指数;要么nil
立即返回(或默认),要么以相反的顺序从集合的末尾开始;
在未提供默认值时添加一个额外的主体(nil
未通过时添加);
可能使用循环/递归形式每次不传递最后一个默认参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句