Haskell中的递归和并行性

时间:2016-11-14 20:44:40

标签: haskell recursion parallel-processing

我试图理解Haskell中的并行是如何工作的,我在Control.Parallel文档中找到了以下示例。

'red'

但是我找不到这个递归如何工作的解释:parEstimate(x:y:xs),因为我发现的所有例子都只包含两个参数。 这就是我无法找到如何运行此功能的原因。这就是我的方式:

import Control.Parallel

-- Equation for the upper hemisphere of the unit circle

circle :: Double -> Double
circle x = sqrt (abs(1 - x^2))

-- Calculate the area of a right-handed Riemann rectangle

area :: Double -> Double -> Double
area x1 x2 = (x2 - x1) * circle x2

-- Recursively add the areas of the Riemann rectangles

parEstimate :: [Double] -> Double
parEstimate (x:[]) = 0
parEstimate (x:y:[]) = area x y
parEstimate (x:y:xs) =
smaller `par` (larger `pseq` smaller + larger)
  where smaller = area x y
        larger = parEstimate (y:xs)

但不确定,如果它是正确的。 另外我想基于这个例子实现函数计算定积分。

1 个答案:

答案 0 :(得分:3)

递归本质上是一个简单的fold - 类似的递归方案;如果这是纯粹的顺序,你可以把它写成

seqEstimate :: [Double] -> Double
seqEstimate (x:[]) = 0
seqEstimate (x:y:[]) = area x y
seqEstimate (x:y:xs) = smaller + larger
    where smaller = area x y
          larger = seqEstimate (y:xs)

(事实上,您可能只需使用zipWith代替:seqEstimate xs = sum (zipWith area xs (tail xs))。)

并行化版本类似。但是,这一次,par用于表示左侧(smaller)可以与右侧(pseq larger (smaller + larger))并行评估。无论编译器是否选择这样做,并且无论smallerlarger之前还是之后完成smaller + larger,都将正确计算{{1}}的总和。

相关问题