僅供參考,請閱讀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