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…
- Import the parallel strategies as follows:
import Control.Parallel.Strategies
- 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
- The first few characters of the printed output are shown here after compiling and running the code as follows:
- Compile the code with the
threaded
andrtsopts
flags enabled as follows:$ ghc -O2 --make Main.hs -threaded -rtsopts
- Run the code by specifying the number of cores as follows:
$ ./Main +RTS -N2 [0,3644720378636855297,1420199564594381824,-9091195533231350103,-3969065814844243968,5699158338132413177,5185631055696798720,-1664423011715345679,-5301432476323807232,-6822228826283293807,-3978116359327587328,-2988467747382449959...