Clojure - Splitting a vector

前端 未结 3 946
甜味超标
甜味超标 2021-01-28 05:23

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,

(fo         


        
相关标签:
3条回答
  • 2021-01-28 05:48

    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]]
    
    0 讨论(0)
  • 2021-01-28 05:51
    (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)
    
    0 讨论(0)
  • 2021-01-28 05:53

    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.

    0 讨论(0)
提交回复
热议问题