假设我有一个谓词需要两个项目,并返回false的真假。我想在谓词的返回true的序列中的每个连续对之间插入一个项目。我提出了一些解决方案,但是我想知道在Clojure中以何种惯用方式来实现它的功能?在满足谓词的序列中,在两个项目之间插入项目?
5
A
回答
3
这是我尝试它:
(defn interpose-predicated [pred in coll]
(if (next coll)
(->> coll
(partition 2 1)
(mapcat (comp next #(if (apply pred %) (interpose in %) %)))
(cons (first coll)))
coll))
4
我的第一稿,会是这样的
(defn insert-between [pred inter coll]
(lazy-seq
(when-let [s (seq coll)]
(cons (first s)
(mapcat (fn [[left right]]
(if (pred left right)
[inter right]
[right]))
(partition 2 1 s))))))
user> (insert-between < :less [1 6 7 4 3])
(1 :less 6 :less 7 4 3)
似乎工作,但我特别壳体内的第一个元素在一个丑陋的方式我想你可以解决这个问题。无论如何,这个解决方案肯定能够得到改善。
3
这是通常的SO [clojure]比赛提出最简洁的解决方案。 :-)我通常不会赢,但我在这个过程中学到了很多东西。总之,这里是我的解决方案:
(defn interpose-p [[a b & _ :as s] d p]
(when-not (empty? s)
(if (and (not (nil? b)) (p a b))
(cons a (cons d (interpose-p (rest s) d p)))
(cons a (interpose-p (rest s) d p)))))
(interpose-p [1 2 3 2 1 2 3] "," <)
(1 "," 2 "," 3 2 1 "," 2 "," 3)
更新:尽管讨论过,这里是一个更新的解决方案考虑到了大家的意见。假设我对懒惰seq的理解是正确的,这次应该是相当的工业强度。它是从懒惰seq讨论here的模板。
(defn interpose-p
[pred coll sep]
(let [f (fn [c]
(when-let [[a b & _ :as s] (seq c)]
(if (and b (pred a b))
(list* a sep (interpose-p pred (rest s) sep))
(list* a (interpose-p pred (rest s) sep)))))]
(lazy-seq (f coll))))
相关问题
- 1. 在django项目中的两个应用程序之间导入
- 2. 在ListView项目之间插入元素
- 3. 在词典的开头插入项目
- 4. 满足一元Prolog谓词
- 5. 如何在Scala中查找满足两个谓词的两个元素?
- 6. 在满足谓词(斯卡拉)
- 7. 如何在我的列表项目之间插入空格?
- 8. Shopify - 在项目列表之间插入图像
- 9. 如何在列表项目之间插入换行符
- 10. 两个项目之间的跨项目引用
- 11. 在列表中已经添加一个项目的每个项目之间
- 12. 一旦第一个observable中的某个项目满足谓词,我该如何合并observables?
- 13. 两个.txt之间的项目配对
- 14. 如何在列表中插入项目
- 15. 从两个项目之间获取项目
- 16. 在两个列表之间移动可编辑项目?
- 17. AngularJS在两个选择列表之间移动项目
- 18. ASP.NET mvc:在两个列表框之间移动项目
- 19. 在两个recyclerView列表之间交换项目
- 20. Oracle - 选择其中一列满足谓词的所有列表
- 21. 在两个Web项目之间共享应用程序设置
- 22. 未能满足项目要求
- 23. 矢量满足在r中的项目的条件要素的
- 24. 如何在数组中插入其他两者之间的项目
- 25. 在两个项目中导入partials
- 26. 查找与谓词匹配的索引序列中的最后一个项目
- 27. 在矩阵中插入一个项目
- 28. 排列具有有限的项目之间的两个阵列
- 29. 如何在词典列表中添加两个项目
- 30. 在多个项目之间而不是在两个项目之间分配算法(篮球)?
我刚刚交了这4clojure - http://www.4clojure.com/problem/132 –