Clojure需要一段时间和n个以上的项目
Clojure的惯用方法是什么来实现下面的Clojure需要一段时间和n个以上的项目,clojure,Clojure,Clojure的惯用方法是什么来实现下面的take-while-and-n-more: => (take-while-and-n-more #(<= % 3) 1 (range 10)) (0 1 2 3 4) 以下代码是Clojurestake while的修改版本。当Clojurestake while返回nil作为默认情况时(当谓词不匹配时),此函数调用take在谓词失败后获取附加项 请注意,与使用拆分的版本不同,此版本只遍历序列一次 (defn take-while-an
take-while-and-n-more
:
=> (take-while-and-n-more #(<= % 3) 1 (range 10))
(0 1 2 3 4)
以下代码是Clojures
take while
的修改版本。当Clojurestake while
返回nil
作为默认情况时(当谓词不匹配时),此函数调用take
在谓词失败后获取附加项
请注意,与使用拆分的版本不同,此版本只遍历序列一次
(defn take-while-and-n-more
[pred n coll]
(lazy-seq
(when-let [s (seq coll)]
(if (pred (first s))
(cons (first s) (take-while-and-n-more pred n (rest s)))
(take n s)))))
对于相同的参数,我将使用,这相当于获取take while和drop while的结果:
(defn take-while-and-n-more [pred n coll]
(let [[head tail] (split-with pred coll)]
(concat head (take n tail))))
还有另一种方式:
(defn take-while-and-n-more [pred n coll]
(let [[a b] (split-with pred coll)]
(concat a (take n b))))
concat返回一个惰性序列,您是对的。我编辑了我的答案。但是,使用拆分将导致遍历序列中匹配谓词的部分两次。
(defn take-while-and-n-more [pred n coll]
(let [[a b] (split-with pred coll)]
(concat a (take n b))))