How to do parallel “either-side” short-circuiting with “and” and “or”

本秂侑毒 提交于 2019-12-05 01:37:01

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

This is provided by Conal Elliott's unamb package. It uses unsafePerformIO under the covers to evaluate both a && b and b && a on separate threads, and returns when either produces a result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!