仅供参考,请阅读Simon Marlow书中的Parallel
一章。 http://chimera.labs.oreilly.com/books/1230000000929/ch02.html#sec_par-eval-whnf
正如其他人所说的那样,使用Eval
中的par
monad似乎是正确的方法。 这是您的问题的简化视图。您可以使用+RTS -threaded -RTS
进行编译来测试它,然后可以使用Thread Scope来分析您的性能。
import Control.Parallel.Strategies
import Data.List (maximumBy, subsequences)
import Data.Ord
isPalindrome :: Eq a => [a] -> Bool
isPalindrome xs = xs == reverse xs
-- * note while subsequences is correct, it is asymptotically
-- inefficient due to nested foldr calls
getLongestPalindrome :: Ord a => [a] -> Int
getLongestPalindrome = length . maximum' . filter isPalindrome . subsequences
where maximum' :: Ord a => [[a]] -> [a]
maximum' = maximumBy $ comparing length
--- Do it in parallel, in a monad
-- rpar rpar seems to fit your case, according to Simon Marlow's book
-- http://chimera.labs.oreilly.com/books/1230000000929/ch02.html#sec_par-eval-whnf
main :: IO()
main = do
let shorter = [2,3,4,5,4,3,2]
longer = [1,2,3,4,5,4,3,2,1]
result = runEval $ do
a <- rpar $ getLongestPalindrome shorter
b <- rpar $ getLongestPalindrome longer
if a > b -- 'a > b' will always be false in this case
then return (a,"shorter")
else return (b,"longer")
print result
-- This will print the length of the longest palindrome along w/ the list name
-- Don't forget to compile w/ -threaded and use ThreadScope to check
-- performance and evaluation
那么我在这里错了什么?@bheklilr – Xie
这对我来说编写得很好。我不认为'longestPalindr'会做你想做的事情。另外,由于不涉及真正的IO,因此考虑使用'par'和'seq'可能更明智,然后让运行时为您平行化,而不是使用'forkIO'。 – thumphries
'longestPalindr'获得一个字符串中最长的回文。但无论如何,我对如何使用'par'与它决斗感兴趣。你能告诉我怎么做吗?@bheklilr – Xie