sunspots
sunspots

Reputation: 1057

Building a nested vector in Clojure

My goal is to build a nested vector of dimension n consisting of a single element p. As an example let me choose n=2 and p=1, so the output would be:

   [[1 1] [1 1]]

Upvotes: 0

Views: 571

Answers (3)

mishadoff
mishadoff

Reputation: 10789

(defn vec-of-dim [n e]
  (->> (repeat n e)
       (into [])
       (repeat n)
       (into [])))

Upvotes: 0

Chuck
Chuck

Reputation: 237110

I think what you want is (->> p (repeat n) vec (repeat n) vec).

Upvotes: 4

Leonid Beschastny
Leonid Beschastny

Reputation: 51490

Probably, you want something like this:

(defn square-matrix [n p]
  (->> p (repeat n) (repeat n)))

Or, if you need vectors (not seqs):

(defn square-matrix [n p]
  (->> p (repeat n) vec (repeat n) vec))

Upvotes: 4

Related Questions