Zip two lists in clojure into list of concatenated strings

被刻印的时光 ゝ 提交于 2019-12-19 18:49:40

问题


Instead of zip-mapping two lists to get:

(zipmap ["a","b","c"] ["c","d","e"]) = {"c" "e", "b" "d", "a" "c"} 

I want to concatenate the first element of the first list with the first element of the second list and so on to get:

("ce","bd","ac") 

or in the reverse order.


回答1:


You can do that with map. map can take multiple collections, it takes the next element from each collection and passes them into the function passed as the first argument (stopping when one of the collections runs out). So you can pass in a function that takes n arguments, and n collections.

The expression

(map str ["a" "b" "c"] ["c" "d" "e"])

will call str first with "a" and "c", then with "b" and "d", then with "c" and "e". The result will be

("ac" "bd" "ce")

Since str can takes a variable number of arguments it can be used with any number of collections. Passing in four collections, like

(map str ["a" "b" "c"] ["d" "e" "f"] ["g" "h" "i"] ["j" "k" "l"])

will evaluate to

("adgj" "behk" "cfil")


来源:https://stackoverflow.com/questions/7922439/zip-two-lists-in-clojure-into-list-of-concatenated-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!