本文介绍了在Clojure中更改映射行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要修改地图函数行为,以提供不具有最小集合大小但是具有最大值的映射,并为缺失的元素使用零。
I need to modify map function behavior to provide mapping not with minimum collection size but with maximum and use zero for missing elements.
标准行为:
(map + [1 2 3] [4 5 6 7 8]) => [5 7 9]
需要的行为:
(map + [1 2 3] [4 5 6 7 8]) => [5 7 9 7 8]
我写了函数来做到这一点,但似乎不太可扩展varargs。
I wrote function to do this, but it seems not very extensible with varargs.
(defn map-ext [f coll1 coll2]
(let [mx (max (count coll1) (count coll2))]
(map f
(concat coll1 (repeat (- mx (count coll1)) 0))
(concat coll2 (repeat (- mx (count coll2)) 0)))))
有更好的方法吗?
推荐答案
另一个惰性变体,可用于任意数量的输入序列:
Another lazy variant, usable with an arbitrary number of input sequences:
(defn map-ext [f ext & seqs]
(lazy-seq
(if (some seq seqs)
(cons (apply f (map #(if (seq %) (first %) ext) seqs))
(apply map-ext f ext (map rest seqs)))
())))
用法:
user> (map-ext + 0 [1 2 3] [4 5 6 7 8])
(5 7 9 7 8)
user> (map-ext + 0 [1 2 3] [4 5 6 7 8] [3 4])
(8 11 9 7 8)
这篇关于在Clojure中更改映射行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!