Clojure 惰性seq计数的自定义实现

Clojure 惰性seq计数的自定义实现,clojure,Clojure,在下面的示例代码中,我返回一个惰性列表。当有人调用列表上的count时,我希望执行一些任意函数,并返回我喜欢的任何结果 (defn my-range [i limit] (lazy-seq (when (< i limit) (cons i (my-range (inc i) limit))))) (count (my-range 0 9)) returns whatever (定义我的范围[i限制] (续) (当(

在下面的示例代码中,我返回一个惰性列表。当有人调用列表上的count时,我希望执行一些任意函数,并返回我喜欢的任何结果

(defn my-range [i limit]
  (lazy-seq 
   (when (< i limit)
     (cons i (my-range (inc i) limit)))))

(count (my-range 0 9)) returns whatever
(定义我的范围[i限制]
(续)
(当(

我不确定这是否可行:我一直在研究
具体化
,但不知道它是否可以用于这种情况。

你可以这样做,但工作量相当大:你必须自己实现所有与序列相关的接口,并将大部分接口委托给你的惰性seq。这是一张草图:

(defn my-range [i limit]
  (let [ret (lazy-seq 
              (when (< i limit)
                (cons i (my-range (inc i) limit))))]
    (reify
      clojure.lang.Counted
      (count [this] 10)
      clojure.lang.Sequential
      clojure.lang.ISeq
      (first [this] (.first ret))
      (next [this] (.next ret))
      (more [this] (.more ret))
      (cons [this x] (.cons ret x))
      (empty [this] (.empty ret))
      (equiv [this x] (.equiv ret x))
      (seq [this] (.seq ret)))))
(定义我的范围[i限制]
(让[ret(lazy seq
(当(
实际上,
(我的范围13)
返回一个两项序列,该序列声称计数为10,这是您想要的。

其他搜索者,另请参见: