Mapping over a list in parallel

In this recipe, we will be applying the map function in parallel. Given a list of values, we will be using multiple threads to apply a function over each value.

How to do it…

  1. Import the parallel strategies as follows:
    import Control.Parallel.Strategies
  2. Map over a list using the rdeepseq strategy using the following code snippet:
    main = do
      let results = 
                (parMap rdeepseq (^10) [10^10..10^10+10000]) :: [Int]
      print results
  3. The first few characters of the printed output are shown here after compiling and running the code as follows:
  4. Compile the code with the threaded and rtsopts flags enabled as follows:
    $ ghc -O2 --make Main.hs -threaded -rtsopts
    
  5. Run the code by specifying the number of cores as follows:
    $ ./Main +RTS -N2 ...

Get Haskell Data Analysis Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.