我想在Haskell中找到无限列表中的第一个匹配元素。
此代码正常运行:
findPassword passwordHash = (head . filter (checkPassword passwordHash)) allStrings
checkPassword非常长(因为它是一个SHA1哈希值)
checkPassword hash string = (sha1 string) == hash
allStrings只是所有可能字符串的列表:
allStrings = [ c : s | s <- "" : allStrings, c <- ['a'..'z'] ++ ['0'..'9'] ]
我希望此代码并行运行,但如果我用parFilter替换过滤器:
import qualified Control.Parallel.Strategies as S
parFilter p = S.withStrategy (S.evalBuffer 1000 S.rseq) . filter p
它不起作用......你有什么想法吗?这段代码也使用了大量内存,但这是另一个问题。 完整脚本可在此处https://github.com/ThibaudDauce/habreaker
获取答案 0 :(得分:5)
我确定您要使用parBuffer
代替evalBuffer
。
请参阅此SO答案以获得一个很好的解释:
How to choose between parList and parBuffer?
以下是一些演示代码:
import qualified Data.Map.Strict as M
import Control.Parallel.Strategies
import System.Environment
import Debug.Trace
fib 0 = 0
fib 1 = 1
fib n = fib (n-2) + fib (n-1)
fib' n | trace "calling fib" False = undefined
fib' n = fib n
theList = cycle [30,31,32]
firstN :: Int -> [Int]
firstN n = take n $ filter even $ map fib' theList
firstNpar :: Int -> Int -> [Int]
firstNpar n k = take n $ filter even $ runEval $ parBuffer k rseq $ map fib' theList
main = do
(argn : argk : _) <- getArgs
let n = read argn
case argk of
"" -> print $ firstN n
_ -> let k = read argk in
print $ firstNpar n k
示例运行:
prog 20 2 +RTS -N2 -- I only have two cores
prog 20 '' -- run single threaded