3 ms·
Here's 2 Examples (Warning: Didn't run them and could have missed imports). One parallelizing a sudoku solver and the other making a reminder program concurren
by codygman 12y ago
Here's 2 Examples (Warning: Didn't run them and could have missed imports).
One parallelizing a sudoku solver and the other making a reminder program concurrent. Both are from Parallel and Concurrent Programming In Haskell[0].
Sequential version[1]:
import Sudoku
import Control.Exception
import System.Environment
import Data.Maybe
main :: IO ()
main = do
[f] <- getArgs
file <- readFile f
let puzzles = lines file
solutions = map solve puzzles
print (length (filter isJust solutions))
Parallel version[2]:
import Sudoku
import Control.Exception
import System.Environment
import Data.Maybe
import Control.Parallel.Strategies (parMap) -- line that changed
main :: IO ()
main = do
[f] <- getArgs
file <- readFile f
let puzzles = lines file
solutions = runEval (parMap solve puzzles) -- line that changed
print (length (filter isJust solutions))
Here's an example making a small reminder program concurrent:
Sequential[3]:
import Control.Concurrent
import Text.Printf
import Control.Monad
main =
forever $ do
s <- getLine
forkIO $ setReminder s
setReminder :: String -> IO ()
setReminder s = do
let t = read s :: Int
printf "Ok, I'll remind you in %d seconds\n" t
threadDelay (10^6 * t)
printf "%d seconds is up! BING!\BEL\n" t
Concurrent[4]:
import Control.Concurrent
import Text.Printf
import Control.Monad
main = loop
where
loop = do
s <- getLine
if s == "exit"
then return ()
else do forkIO $ setReminder s
loop
setReminder :: String -> IO ()
setReminder s = do
let t = read s :: Int
printf "Ok, I'll remind you in %d seconds\n" t
threadDelay (10^6 * t)
printf "%d seconds is up! BING!\BEL\n" t
0: http://chimera.labs.oreilly.com/books/1230000000929/index.html http://chimera.labs.oreilly.com/books/1230000000929/index.ht...
1: http://chimera.labs.oreilly.com/books/1230000000929/ch02.html#import_sudoku_i http://chimera.labs.oreilly.com/books/1230000000929/ch02.htm...
2: http://chimera.labs.oreilly.com/books/1230000000929/ch02.html#par-eval_00000169 http://chimera.labs.oreilly.com/books/1230000000929/ch02.htm...
3: http://chimera.labs.oreilly.com/books/1230000000929/ch07.html#import_control_id3 http://chimera.labs.oreilly.com/books/1230000000929/ch07.htm...
4: http://chimera.labs.oreilly.com/books/1230000000929/ch07.html#sec_reminders http://chimera.labs.oreilly.com/books/1230000000929/ch07.htm...
- sanderjd 12y agoThanks!