作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
仍然试图将我的头环绕在 Clojure 上。我可以看到如何在 Haskell、Python 等中实现以下内容,但还不明白如何在 Clojure 中编写它。感谢有人可以向我展示基本结构。伪代码如下。
a = get_a
if (a == bad_value) then throw exception_a
b = get_b
if (b == bad_value) then throw exception_b
c = get_c
if (c == bad_value) then throw exception_c
...
do_action_with a b c
最佳答案
有多种可能性——这里有一些作为开始:
;;; 1. direct translation
; _ is the idiomatic "I don't care" identifier in Clojure
(let [a (get-a)
_ (if (= a bad-value) (throw (Exception. "Foo!")))
b (get-b)
_ (if (= b bad-value) (throw (Exception. "Foo!")))
...]
(do-action-with a b ...))
;;; 2. abstract the pattern away
(defmacro disallow
([expr val] ; binary version with default exception type;
; omit if explicit type is to be required
(disallow (list* &form [Exception]) &env expr val Exception))
([expr val e]
`(let [actual# ~expr]
(if (= actual# ~val)
(throw (new ~e (str "Value " ~val " not allowed.")))
actual#))))
(let [a (disallow (get-a) ExceptionA)
b (disallow (get-b) ExceptionB)
...]
...)
;;; 3. monadic short-circuiting
(use '[clojure.contrib.monads :only [domonad maybe-m]])
; ...now do it more or less as in Haskell;
; you can use :when in domonad for monads with m-zero
; -- the syntax is that of for / doseq:
(doseq [sym '[a b c]] (intern *ns* sym (atom 0)))
(domonad maybe-m
[a @a
:when (pos? a)
b @b
:when (neg? b)
c @c
:when (not (zero? c))]
(* a b c))
; => 0
(dorun (map reset! [a b c] [3 -2 1]))
(domonad maybe-m
; same as above
)
; => -6
关于clojure - 基本Clojure : How to do a series of if-then?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3553288/
我是一名优秀的程序员,十分优秀!