[Cs254f11] 2D vectors
Lee Spector
lspector at hampshire.edu
Tue Oct 4 17:01:44 EDT 2011
In response to some off-list questions I put together a little code to show how one might represent a 2D grid as a vector of vectors, with the internal vectors being rows of the grid. You could put anything in the actual grid locations, and unlike 2D arrays in many languages there could be different types of things in each location.
I'm sharing this with the class list in case anyone else finds it handy. I don't show the return values here, but you could just evaluate it expression by expression in clooj to see what it does:
(ns vec2D)
(defn getXY
"Returns the contents of location (x, y) in a 2D vector v2D."
[v2D x y]
(get (get v2D x) y))
(defn setXY
"Returns a 2D vector like v2D but with newval at location (x, y)."
[v2D x y newval]
(assoc v2D
x
(assoc (get v2D x)
y
newval)))
(defn procXY
"Returns a 2D vector like v2D but with location (x, y) filled
with the result of calling procfn on the old contents of
location (x, y)."
[v2D x y procfn]
(setXY v2D x y (procfn (getXY v2D x y))))
(def myvec2D
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]])
myvec2D
(setXY myvec2D 2 2 8)
(procXY myvec2D 2 2 inc)
(def altered-vec2D
(-> myvec2D
(setXY 2 2 8)
(procXY 2 2 inc)
(procXY 0 0 dec)
(procXY 3 1 #(+ % 23))))
altered-vec2D
(for [i (range 5)]
(for [j (range 5)]
(if (zero? (getXY altered-vec2D i j))
100
(getXY altered-vec2D i j))))
(def mysetvec2D
[[#{} #{} #{} #{} #{}]
[#{} #{} #{} #{} #{}]
[#{} #{} #{} #{} #{}]
[#{} #{} #{} #{} #{}]
[#{} #{} #{} #{} #{}]])
(-> mysetvec2D
(procXY 2 2 #(conj % :apple))
(procXY 2 3 #(conj % :banana)))
--
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