Clojure在take-while-and-n-more下面实现的惯用方法是什么:
=> (take-while-and-n-more #(<= % 3) 1 (range 10))
(0 1 2 3 4)
Run Code Online (Sandbox Code Playgroud)
我的尝试是:
(defn take-while-and-n-more [pred n coll]
(let
[take-while-result (take-while pred coll)
n0 (count take-while-result)]
(concat
take-while-result
(into [] (take n (drop n0 coll))))))
Run Code Online (Sandbox Code Playgroud)
我会使用split-with,这相当于获取相同参数的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))))
Run Code Online (Sandbox Code Playgroud)