Haskell call function from main without using the return value

Few days ago I was stuck at some issue:
I wanted to do some profiling of ordinary fibonacci function written in Haskell but I didn’t wanted to display the result (using main function, from Main module). Guys from #haskell irc channel (irc.freenode.net) were very helpful and they guided me to evaluate and rnf

module Main where

import Control.Parallel.Strategies
import Control.Exception

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib(n - 1) + fib(n - 2)

main = do
   evaluate(rnf (fib 32))

or, using function composition:

module Main where

import Control.Parallel.Strategies
import Control.Exception

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib(n - 1) + fib(n - 2)

eval = evaluate . rnf
main = do
   eval(fib 32)

ghc --make Fib.hs
time ./Fib

and for better performance:

ghc --make -O2 Fib.hs
time ./Fib

Advertisement

2 Responses to “Haskell call function from main without using the return value”

  1. gcarlos Says:

    what do exactly rnf?

  2. alinpopa Says:

    rnf is forcing evaluation (since haskell is lazy, this might not happen by default and we need that in order to eliminate the stack space )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.