Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Par function underlying logic

How does the par function work? Its signature is:

par :: a -> b -> b.

But this is strange. Why isn't it:

par :: (a -> b) -> a -> b

(get function, execute it in new thread and return result) ?

Another question, is this normal haskell multithreading??

enter image description here

like image 489
dev1223 Avatar asked May 30 '14 12:05

dev1223


1 Answers

par is for speculative parallelism, and relies on laziness.

You speculate that the unevaluated a should be computed while you're busy working on b.

Later in your program you might refer to a again, and it will be ready.

Here's an example. We wish to add 3 numbers together. Each number is expensive to compute. We can compute them in parallel, then add them together:

main = a `par` b `par` c `pseq` print (a + b + c)
    where
        a = ack 3 10
        b = fac 42
        c = fib 34

fac 0 = 1
fac n = n * fac (n-1)

ack 0 n = n+1
ack m 0 = ack (m-1) 1
ack m n = ack (m-1) (ack m (n-1))

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
like image 193
Don Stewart Avatar answered Sep 22 '22 15:09

Don Stewart