Skip to content

Commit

Permalink
Actually use parallelism in Haskell exercise
Browse files Browse the repository at this point in the history
Kinda forgot that in the original commit. Whoops.
  • Loading branch information
Peter Minten committed Oct 30, 2013
1 parent f8b7354 commit 97ac511
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion assignments/haskell/parallel-letter-frequency/example.hs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
module Frequency (frequency) where

import Control.Monad.Par (IVar, Par)
import qualified Control.Monad.Par as Par
import Data.Char (isLetter, toLower)
import Data.List.Split (chunksOf)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
Expand All @@ -9,7 +12,15 @@ import qualified Data.Text as T
-- | Compute the frequency of letters in the text using the given number of
-- parallel workers.
frequency :: Int -> [Text] -> Map Char Int
frequency _workers = Map.unionsWith (+) . map countLetters
frequency workers texts = Par.runPar $ do
let chunks = chunksOf workers texts
ivars <- mapM (\_ -> Par.new) chunks
mapM_ (Par.fork . work) $ zip chunks ivars
freqs <- mapM Par.get ivars
return $ Map.unionsWith (+) freqs

work :: ([Text], IVar (Map Char Int)) -> Par ()
work (texts, ivar) = Par.put ivar . Map.unionsWith (+) . map countLetters $ texts

countLetters :: Text -> Map Char Int
countLetters = T.foldl' process Map.empty
Expand Down

0 comments on commit 97ac511

Please sign in to comment.