Created
February 27, 2014 01:34
-
-
Save dmjio/9242523 to your computer and use it in GitHub Desktop.
parallel longest palindrome checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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 | |
then return (a,"a") | |
else return (b,"b") | |
print result | |
-- Don't forget to compile w/ -threaded and use ThreadScope to check | |
-- performance and evaluation | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment