如何链接在Clojure的承诺 [英] How to chain promises in Clojure
问题描述
在Scala中,您可以使用 map
和 flatMap
为未来的成功结果运行函数。 / p>
val x:Future [Int] = ...
val y:Future [String] = x.map _.toString)
有比这更好的Clojure类似:
(def x(promise))
(def y(future(str @x)))
在等待传递 x
时,上述是否会阻塞一个线程? p>
你的clojure代码不会阻塞,直到你尝试dref的值y ie
(def x(promise)); wont block
(def y(future(str @x))) y);将阻止
至于类比,代码看起来不错。但是如果你想要某种更具说明性的链接期货,这是概念上的减少,那么你可以使用 reduce
,如下所示:
(def x(promise))
(def final(reduce#(future(%2 @%1))
x
[inc dec(partial + 10)str]))
(deliver x 10)
@final => 20
你甚至可以想出一个类似于线程的宏 - >, - >>
宏,但是为每个线程表达式创建future,但是我认为这将是一个overkill,当你可以使用normal函数。 $ b
In Scala, you can use map
and flatMap
to run functions on the successful result of a future.
val x: Future[Int] = ...
val y: Future[String] = x.map(_.toString)
Is there a better Clojure analogue to this than:
(def x (promise))
(def y (future (str @x)))
Won't the above block a thread while it waits for delivery of x
?
Your clojure code won't block until you try to dref the value of y i.e
(def x (promise)) ;wont block
(def y (future (str @x))) ;wont block
(print @y) ;will block
As far as analogy is concerned, the code looks fine. But if you want some sort of more declarative way of chaining futures, which is conceptually reduction, then you could use reduce
as shown below:
(def x (promise))
(def final (reduce #(future (%2 @%1))
x
[inc dec (partial + 10) str]))
(deliver x 10)
@final => "20"
You could even come-up with a macro which is similar to threading ->, ->>
macros but create futures for each threaded expression, but I think that would be an overkill when you could do this using normal function.
这篇关于如何链接在Clojure的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!