我可以在Clojure记录中创建可变状态吗? [英] Can I create mutable state inside Clojure records?

查看:72
本文介绍了我可以在Clojure记录中创建可变状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用Clojure记录映射到我的程序中不断变化的实体。他们是可变的吗?或者你需要在记录中使用额外的参考?我对此感到困惑。

I am considering using Clojure records to map to changing entities in my program. Are they mutable? Or do you need to use extra refs within the records? I am a little confused about this

推荐答案

这很值得观看 Rich Hickey关于身份和状态的精彩视频

记录设计为 immutable 并将某个值的状态存储为值。

Records are designed to be immutable and store the state of something as a value.

要建模更改实体的状态,建议您使用代表当前状态的参考表示不可变值。您可以将记录用于不可变状态,但通常只是使用简单的地图更简单。

To model the state of a changing entity, I'd recommend using a ref that refers to an immutable value that represents the current state. You can use records for the immutable state, but often it's simpler just to use a simple map.

一个简单的例子,可变状态是游戏的记分牌:

A simple example, where the mutable state is a scoreboard for a game:

; set up map of current scores for each player
(def scores 
  (ref 
    {:mary 0 
     :joe  0   }))

; create a function that increments scores as a side effect
(defn add-score [player amount]
  (dosync
    (alter scores update-in [player] + amount)))

; add some scores
(add-score :mary (rand-int 10))
(add-score :joe (rand-int 10))

; read the scores
@scores
=> {:mary 6, :joe 1}

这篇关于我可以在Clojure记录中创建可变状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆