Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Haskell: First parallel Haskell program

Haskell supports Parallel and multi core programming. Following is an example of small parallel program application. I am not going to explain any details, just want to show how easy it is to develop parallel programs in Haskell. We can write parallel programs by using `par` expression.


Sample.hs
import Control.Parallel

main = a `par` b `par` c `pseq` print (a + b + c)
where
a = ackermann 3 10
b = factorial 20
c = fibonacci 20

factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n-1)

ackermann :: Integer -> Integer -> Integer
ackermann m n
| (m==0) = n+1
| (m > 0) && (n==0) = ackermann (m-1) 1
| (m > 0) && (n > 0) = ackermann (m-1) (ackermann m (n-1))


fibonacci :: Integer -> Integer
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n-1) + fibonacci (n-2)


Compiling with -threaded and optimisations on:
$ ghc -O2 --make Sample.hs -threaded -rtsopts
[1 of 1] Compiling Main ( Sample.hs, Sample.o )
Linking Sample ...


Run multi core program using 2 cores.

$ time ./Sample +RTS -N2
2432902008176654954

real 0m1.309s
user 0m1.365s
sys 0m0.120s






Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell: First parallel Haskell program

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×