如何做平行的“任何一方”短路与“和”和“或” [英] How to do parallel "either-side" short-circuiting with "and" and "or"

查看:161
本文介绍了如何做平行的“任何一方”短路与“和”和“或”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell有一个并行的和方法吗?

  parAnd :: Bool  - >布尔 - > Bool 

这样

 (a`parAnd` b)

会触发a和b的评估并行并在a或b评估为false(而不是等待另一个)时立即返回false?

有什么方法可以实现这样的事情吗?

解决方案

通常情况下,这是不可能的。你可以做一些事情,比如:
$ b $ pre $ a $ par $ b $ p $ a
$ / code>

但如果 b 的计算结果为 False a 仍然完全评估。



然而,这可以通过明确的选择运营商由他的功能反应规划(FRP)实施 Conal Elliott 创建。它可以在Hackage上以 unamb 包的形式获得,并且完全符合您的需求。特别是,它包含

   -  |将一个二进制交换操作转换为以
- parallel方式尝试两个订单的操作。当有特殊情况下不需要
- 评估两个参数时很有用。
- ...
parCommute ::(a - > a - > b) - > a - > a - > b

也直接定义 pand por 和其他类似的可交换函数,例如

  pand undefined False  - > ; False 
pand False undefined - >假


Does haskell have a parallel "and" method

parAnd :: Bool -> Bool -> Bool

such that

(a `parAnd` b)

will spark the evaluation of a and b in parallel and return false as soon as either a or b evaluates to false (and not wait for the other one)?

Is there some way to implement such a thing?

解决方案

Normally, this is not possible. You can do something like

a `par` b `pseq` (a && b)

but if b evaluates to False, a is still fully evaluated.

However, this is possible with the unambiguous choice operator created by Conal Elliott for his Functional Reactive Programming (FRP) implementation. It's available on Hackage as unamb package and does exactly what you want. In particular, it contains

-- | Turn a binary commutative operation into one that tries both orders in
-- parallel. Useful when there are special cases that don't require
-- evaluating both arguments.
-- ...
parCommute :: (a -> a -> b) -> a -> a -> b

and also directly defines pand,por and other similar commutative functions, such that

pand undefined False   -> False
pand False undefined   -> False

这篇关于如何做平行的“任何一方”短路与“和”和“或”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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