[Cs254f11] 'Un-nesting' sequences to be used in assoc

Lee Spector lspector at hampshire.edu
Tue Dec 6 20:31:45 EST 2011


The first way that occurred to me to do this uses the somewhat fancy "partial" function:

(def maxboard {}) ;; I'm assuming this is the initial board that you want to assoc the new entries into

(def maxvec '([[0 0] 1] [[0 1] 1] [[1 2] 1] [[0 3] 1])) ;; and these are the new entries, in pairs

(apply (partial assoc maxboard) (apply concat maxvec))

=> {[0 3] 1, [1 2] 1, [0 1] 1, [0 0] 1}

There are of course many other ways. Here's one that uses loop; it's big but maybe clear if you've been using loop:

(loop [v maxvec b maxboard]
  (if (empty? v)
    b
    (recur (rest v)
           (assoc b (first (first v)) (second (first v))))))

Here's a pretty funky completely different approach:

(apply merge (conj (for [[k v] maxvec] (assoc {} k v)) maxboard))

That one makes a little 1-entry map for each key/value pair and then merges them all together and with the pre-existing maxboard.

After all of that, this is perhaps the simplest and the clearest:

(merge maxboard (zipmap (map first maxvec) (map second maxvec)))

Does one of these suit your purposes?

 -Lee


On Dec 6, 2011, at 7:59 PM, Maxwell William Fair Levit wrote:

> Hi, I'm trying to get a sequence of vectors of vectors that looks like this:
> 
> ([[0 0] 1] [[0 1] 1] [[1 2] 1] [[0 3] 1])
> 
> to be the key value pairs of a call to assoc
> 
> The map I'm associng into has key values that are two place vectors, so if I
> were to manualy input a mapping it would look like
> 
> (assoc board [0 0] 1 [2 2] 5) and so on.
> 
> Is there some way to un-sequence my list? Keep in mind that this is a specific
> arbitrary example, and my  sequence of vectors will vary in length throughout a
> single execution.
> 
> -Max
> 
> _______________________________________________
> Cs254f11 mailing list
> Cs254f11 at lists.hampshire.edu
> https://lists.hampshire.edu/mailman/listinfo/cs254f11

--
Lee Spector, Professor of Computer Science
Cognitive Science, Hampshire College
893 West Street, Amherst, MA 01002-3359
lspector at hampshire.edu, http://hampshire.edu/lspector/
Phone: 413-559-5352, Fax: 413-559-5438



More information about the Cs254f11 mailing list