Skip to content

Instantly share code, notes, and snippets.

@dmjio
Created February 27, 2014 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmjio/9242523 to your computer and use it in GitHub Desktop.
Save dmjio/9242523 to your computer and use it in GitHub Desktop.
parallel longest palindrome checker
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