Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure需要一段时间和n个以上的项目_Clojure - Fatal编程技术网

Clojure需要一段时间和n个以上的项目

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

Clojure的惯用方法是什么来实现下面的
take-while-and-n-more

=> (take-while-and-n-more #(<= % 3)  1 (range 10))
(0 1 2 3 4)

以下代码是Clojures
take while
的修改版本。当Clojures
take 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))))