【问题标题】:How to map reduce referential data in functional programming如何在函数式编程中映射reduce引用数据
【发布时间】:2016-03-18 22:23:51
【问题描述】:

我想使用函数式编程制作基于图块的游戏。

游戏有 6 块瓷砖,每块瓷砖可以占据一块。这是我的数据结构:

{
 :pieces {
          1 { :type 'p' }
          2 { :type 'r' }
          }
 :tiles [{}
         {}
         {:current 1}
         {}
         {:current 2}
         {}]
 }

这是游戏图块的序列表示:

'00p0r0'

我需要一个将这个串行数据转换成我的数据结构的函数。

【问题讨论】:

  • 首先请在您的标签中选择一种语言?那里的地图看起来像 clojure - 那么 haskell 是如何发挥作用的呢?也请添加您到目前为止尝试过的代码。
  • 语言无关紧要,我想知道你是如何在功能风格上做到这一点的。 @cfrick

标签: haskell clojure functional-programming monads


【解决方案1】:

有一些方法可以优化它,但它应该给你正确的想法。请参阅下面的代码以获取替代建议。

这里有趣的是,您将一个固定的瓦片模型映射到一个可变的片类型集。将片段模型制作为固定数组也会有效率。

注意:输入必须是字符串,而不是像您的示例中那样使用单引号:(例如 "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))

备用 根据定义,输入字符串隐含地包含您想要的所有信息。可以定义一系列函数,将序列化字符串作为电路板状态,随时用新字符串替换它。只是一个建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多