haskell - 数据并行 Haskell 前缀和

标签 haskell parallel-processing multicore data-parallel-haskell prefix-sum

我正在使用一些 Data Parallel Haskell 代码,发现自己需要 prefix sum 。但是我在 dph package 中没有看到任何基本运算符对于前缀和。

我自己推出了,但是,由于我是 dph 的新手,我不确定它是否正确利用了并行化:

{-# LANGUAGE ParallelArrays #-}
{-# OPTIONS_GHC -fvectorise #-}

module PrefixSum ( scanP ) where
import Data.Array.Parallel (lengthP, indexedP, mapP, zipWithP, concatP, filterP, singletonP, sliceP, (+:+), (!:))
import Data.Array.Parallel.Prelude.Int ((<=), (-), (==), Int, mod)
-- hide prelude
import qualified Prelude 

-- assuming zipWithP (a -> b -> c) given 
-- [:a:] of length n and
-- [:b:] of length m, n /= m
-- will return
-- [:c:] of length min n m

scanP :: (a -> a -> a) -> [:a:] -> [:a:]
scanP f xs = if lengthP xs <= 1
                then xs
                else head +:+ tail
  where -- [: x_0, x_2, ..., x_2n :]
        evens = mapP snd . filterP (even . fst) $ indexedP xs
        -- [: x_1, x_3 ... :]
        odds = mapP snd . filterP (odd . fst)  $ indexedP xs
        lenEvens = lengthP evens
        lenOdds = lengthP odds
        -- calculate the prefix sums [:w:] of the pair sums [:z:]
        psums = scanP f $ zipWithP f evens odds
        -- calculate the total prefix sums as 
        -- [: x_0, w_0, f w_0 x_2, w_1, f w_1 x_4, ..., 
        head = singletonP (evens !: 0)
        body = concatP . zipWithP (\p e -> [: p, f p e :]) psums $ sliceP 1 lenOdds evens
        -- ending at either
        --    ... w_{n-1}, f w_{n-1} x_2n :]
        -- or
        --    ... w_{n-1}, f w_{n-1} x_2n, w_n :]
        -- depending on whether the length of [:x:] is 2n+1 or 2n+2
        tail = if lenEvens == lenOdds then body +:+ singletonP (psums !: (lenEvens - 1)) else body

-- reimplement some of Prelude so it can be vectorised
f $ x = f x
infixr 0 $
(.) f g y = f (g y)

snd (a,b) = b
fst (a,b) = a

even n = n `mod` 2 == 0
odd n = n `mod` 2 == 1

最佳答案

并行前缀扫描为 supported ,事实上,它们是相当基本的。因此,只需传递 (+) 作为关联运算符即可。

关于haskell - 数据并行 Haskell 前缀和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080112/

相关文章:

r - 使用递归将许多图像复制到新文件夹

python - 并行调用 map 的最简单方法?

ios - 为双核 iDevices 编写代码

multicore - 为什么 Go 语句不并行执行?

haskell - Arrow 和 Monad,两个独立的观点来组成计算?

linux - 在 Linux 上安装 wxHaskell 时出现构建错误

r - doParallel "foreach"不一致地从父环境 : "Error in { : task 1 failed - "could not find function. 继承对象..”

haskell - 平行 cabal

haskell - Haskell 如何执行 Beta 转换来派生类型?

无法识别 Haskell DeriveGeneric pragma