- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一款使用大爆炸式编程风格的游戏,其中将整个状态定义为单个数据结构,并通过与单个原子进行交换来管理状态变化。
在游戏中,我们不能信任客户端发送的数据,因此服务器必须预测某些 Action 无效的可能性并加以防范。当一个人编写一个交换世界状态的函数时,它可以从纯粹开始;但是,必须考虑无效请求的可能性。我相信要影响惯用的 Clojure 中的不愉快路径,只需抛出异常即可。所以现在可能是纯函数感染了副作用异常。也许this这是必须的。
(try
(swap! world update-game) ;possible exception here!
(catch Exception e
(>! err-chan e))
我的目标是将副作用推迟到最后一刻。我几乎没有涉足 Haskell 领域,但我知道 Either monad 的概念。当一个人考虑 the happy and unhappy path人们知道总是有这两种可能性。这让我想到 swap!
本身是不够的,因为它忽略了不愉快的路径。这是想法的精神:
(swap-either! err-chan world update-game) ;update-game returns either monad
Clojure 社区是否采用了 any more functional approaches用于处理异常?
最佳答案
在这种情况下,我倾向于采用几种不同的方法。如果在单个位置更新状态,我倾向于使用:
(try
(swap! world update-game) ;possible exception here!
(catch Exception e
(>! err-chan e)
world) ;; <--- return the world unchanged
或者如果它设置在很多地方广告观察者将异常抛回到交换的地方!被调用但不改变状态:
user> (def a (atom 1))
#'user/a
user> (add-watch a :im-a-test (fn [_ _ _ new-state]
(if (even? new-state)
(throw (IllegalStateException. "I don't like even numbers")))))
#object[clojure.lang.Atom 0x5c1dc37e {:status :ready, :val 1}]
user> (swap! a + 2)
3
user> (swap! a + 3)
IllegalStateException I don't like even numbers user/eval108260/fn--108261 (form-init8563497779572341831.clj:2)
关于exception-handling - 在 Clojure 中处理纯度错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805947/
我目前正在设计一种数值算法,作为其运算的一部分,它需要多次更新doubles的向量。由于该算法必须尽可能地节省空间和时间,因此,我不想对传统类型的FP代码进行编码,该FP代码在每次对其进行操作后都会在
monad 构造如何帮助保持纯度(在 Haskell 中),同时做不纯粹的事情?例如,当您给出 print "Hello" 时,您执行的是纯代码还是不纯代码?这是一个非常微妙的细节,但有助于更好地理解
我是一名优秀的程序员,十分优秀!