2013-08-01 30 views
1

這是Clojure中,首先是我的代碼:如何更新2D矢量內的結構值? Clojure的

;cell structure 
(defstruct cell :x :y :highland :lowland :obstacle :ammo :tank) 

;demension 
(def dim 0) 

(defn setdim [num] 
    (def dim num)) 

;create world 
(defn creatworld [] 
    (apply vector 
     (map (fn [_] 
       (apply vector (map (fn [_] (struct cell)) 
            (range dim)))) 
       (range dim)))) 

;initiate coordinate for structure in vector of vector 
;this is not working 
(defn inicoor [world] 
    (map 
    #(assoc % :x i :y j) 
    world)) 

(defn inicoor [world] 
    (dorun (for [i (range 0 dim)] 
      (dorun (for [j (range 0 dim)] 
        (map 
        # (assoc (nth (nth world i) j) :x i :y j))))))) 

所以,我在做什麼是我嘗試使用結構的2D向量來創建一個2D的世界。創建世界之後,我希望啓動x y座標作爲實際座標,就像我在最後一個函數中嘗試的那樣。然而,由於clojure是變量不可變的,它不會改變值...並且它也不會返回新數據的二維矢量... 然後我嘗試使用map ...但我對clojure真的很陌生...幾次嘗試後沒有工作...

任何人都可以告訴我該怎麼做嗎?非常感謝......

地址: 目標結構是這樣的:

[ 00 10 20 30 40 50 ] (this is the first vector) 
    01 11 21 31 41 51 
    02 12 22 32 42 52 
    03 13 23 33 43 53 
    04 14 24 34 44 54 
    05 15 25 35 45 55 

這就是爲什麼我曾經在第一窩環......最常見的方式在Java中做到這一點.. 。

回答

2

普通地圖,你可以說:

(for [y (range 8) x (range 8)] {:x x :y y}) 

得到與他們的座標細胞的一個大名單

更新它們(假設你有一個FN更新單元[單元]:

(map update-cell cells) 

,或者如果你有一些數據和更新它們:

(map update-cell cells (repeat data)) 
  • 數據可能是東西如{:T上的時間:DT MS-since-;最後更新:等其他-東西}

如果你想他們在一個二維網格中,那麼你可以做:

(partition 8 (for [y (range 8) x (range 8)] {:x x :y y})) 

,或者說你有一個(defn make-cell [x y] {:x x :y y}),你可以讓他們:

(map (fn [y] (map (fn [x] (make-cell x y)) (range width))) (range height)) 

然後對其進行更新:

(map (partial map update-cell) cells) 
+0

問題,因爲這是一個二維矢量,所以它應該是這樣的: – zeruitle

+0

[1 2 3 4 5]/1 2 3 4 5/1 2 3 4 5所以,對於我的理解,你的方法是更新1列,然後2列?然後我認爲它不會設置座標正確... – zeruitle

+0

正確的結構應該是這樣的:[00 10 20 30 40]/01 11 21 31 41/02 12 22 32 42 – zeruitle