[英]How to map reduce referential data in functional programming
我想使用函數式編程制作基於圖塊的游戲。
游戲有6個圖塊,每個圖塊可占據一塊。 這是我的數據結構:
{
:pieces {
1 { :type 'p' }
2 { :type 'r' }
}
:tiles [{}
{}
{:current 1}
{}
{:current 2}
{}]
}
這是游戲磁貼的序列表示:
'00p0r0'
我需要一個將該串行數據轉換為我的數據結構的函數。
有多種方法可以優化此效果,但它應該為您提供正確的想法。 請參見下面的代碼以獲取替代建議。
有趣的是,您正在將固定的圖塊模型映射到可變件類型集上。 將零件模型固定為陣列也會有效率。
注意:輸入必須是一個字符串,並且不像您的示例中那樣使用單引號:(例如"00p0r0"
'00p0r0'
)。
(def empty-tile-map
{:piece-count 0
:pieces {}
:tiles (into [] (repeat 6 {}))})
(defn set-tile
"Sets the tile to the index reference to piece"
[arref indx value]
(assoc arref indx {:current value}))
(defn string-to-board-reducer
"Reduce function to create pieces and reference in tile"
[{:keys [piece-count tcount tiles] :as acc} x]
(let [ccnt (inc piece-count)
nmap (assoc acc :tcount (inc tcount))]
(if (> (int x) 48)
(assoc
(assoc
(update-in nmap [:pieces] assoc ccnt {:type x})
:tiles (set-tile tiles tcount ccnt))
:piece-count ccnt)
nmap)
))
(defn string-to-board
[s]
"Take serializated string and generate board"
(dissoc (reduce string-to-board-reducer
(assoc empty-tile-map :tcount 0) (seq s))
:tcount))
備用根據定義,輸入字符串隱式包含您想要的所有信息。 可以定義一系列功能,這些功能將序列化字符串用作板狀態,並在您使用時將其替換為新的字符串。 只是一個建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.