Clojure - Splitting a vector

纵然是瞬间 提交于 2019-12-20 07:13:56

问题


If I have two arguments [[1 2] [3 4]] and [5 6], how can I get to [[1 5] [2 6] [3 5] [4 6]].

I thought I may have to use for so I tried,

(for [x [[1 2] [3 4]]] 
  (for [xx x] 
    (for [y [5 6]] [xx y])))

But it returned ((([1 5] [1 6]) ([2 5] [2 6])) (([3 5] [3 6]) ([4 5] [4 6])))

Any help would be much appreciated. Thanks


回答1:


(mapcat #(map vector % [5 6]) [[1 2] [3 4]])

or using for:

(for [c [[1 2] [3 4]]
      p (map vector c [5 6])]
  p)



回答2:


If I understood your question correctly, your solution is actually very close. You did not need to nest the for expressions explicitly, since doing so creates a new list at every level, instead, just use multiple bindings:

(for [x [[1 2][3 4]]
      xx x
      y [5 6]]
  [xx y])

Which will result in

([1 5] [1 6] [2 5] [2 6] [3 5] [3 6] [4 5] [4 6])

Edit

Now that I finally read your question carefully, I came up with the same answer as @Lee did (mapcat (fn[x] (map vector x [5 6])) [[1 2] [3 4]]), which is the right one and should probably be accepted.




回答3:


This is one (hmm - not particularly elegant) way to get your answer, without using for:

(defn f [x y]
  (let [x' (apply concat x)
        multiples (/ (count x') (count y))
        y' (apply concat (repeat multiples y))]
    (mapv vector x' y')))

(f [[1 2] [3 4]] [5 6])
;;=> [[1 5] [2 6] [3 5] [4 6]]


来源:https://stackoverflow.com/questions/44156063/clojure-splitting-a-vector

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