gpt4 book ai didi

exception-handling - 在 Clojure 中处理纯度错误?

转载 作者:行者123 更新时间:2023-12-04 08:00:09 24 4
gpt4 key购买 nike

我正在开发一款使用大爆炸式编程风格的游戏,其中将整个状态定义为单个数据结构,并通过与单个原子进行交换来管理状态变化。

在游戏中,我们不能信任客户端发送的数据,因此服务器必须预测某些 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com