Saturday, 30 April 2016

Haskell: How to enable GHC extensions


GHC implements some extensions to the Haskell language. By using command line flags or language pragmas, you can enable (or) disable these extensions.

Enable extensions using command line arguments
You can enable an extension by passing command-line flag -XExtensionName to the GHCi command line utilities ghc, ghci, or runghc.

Language Pragma
The LANGUAGE pragma allows language extensions to be enabled in a portable way.

Syntax
{-# LANGUAGE extension1, extension2 ... extensionN #-}

You need to add above line at the starting of your Haskell file.

{-# LANGUAGE ForeignFunctionInterface, CPP #-} : Enables the FFI and preprocessing with CPP

{-# LANGUAGE BangPatterns #-} : Enables Bang patterns

Following Haskell file uses Bang pattern.

listUtil.hs
{-# LANGUAGE BangPatterns #-}
sumList :: [Integer] -> Integer
sumList xs = sumOfEle xs 0

sumOfEle :: [Integer] -> Integer -> Integer
sumOfEle [] acc = acc
sumOfEle (x:xs) !acc = sumOfEle xs (acc+x)

main = print (sumList [1..1000000])

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> main
500000500000


References

Previous                                                 Next                                                 Home

Haskell : Working with infinite structures


Because of the lazy nature of Haskell, we can implement infinite structures.

For example
Statement
Description
[1..]
Represents infinite list of positive integers
[2, 4 ..]
Represents infinite list of even positive integers
[1, 3 ..]
Represents infinite list of odd positive integers

For example, you are working for a company XYZ, it has many products, assume you had customers across globe, to satisfy your customer needs you are maintaining inifinite amount of products. How will you do this.

XYZUtil.hs
type ProductId = Integer
type ISBN = String
type NoOfProducts = Int

data Product = Product {prodId :: ProductId, isbn :: ISBN} deriving Show

getProducts :: ProductId -> ISBN -> [Product]
getProducts prodId isbn = Product prodId isbn : getProducts prodId isbn 

getNProducts :: NoOfProducts -> ProductId -> ISBN -> [Product]
getNProducts num prodId isbn = take num (getProducts prodId isbn)

*Main> :load XYZUtil.hs 
[1 of 1] Compiling Main             ( XYZUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getNProducts 10 123 "ptr"
[Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"}]
*Main> 
*Main> getNProducts 5 5 "ptr123"
[Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"}]
*Main>


getProducts :: ProductId -> ISBN -> [Product]
getProducts prodId isbn = Product prodId isbn : getProducts prodId isbn
getProducts function takes a product id and isbn number, generate infinite list of those products.

getNProducts :: NoOfProducts -> ProductId -> ISBN -> [Product]
getNProducts num prodId isbn = take num (getProducts prodId isbn)
getNProducts return first ‘num’ products from inifinte list.

Get the first product from infinite list
*Main> head (getProducts 1 "aaw1223")
Product {prodId = 1, isbn = "aaw1223"}



Previous                                                 Next                                                 Home

Haskell: Lazy Vs Eager evaluation


a. Most traditional programming languages like C, C++, Java use eager evaluation strategy, where an expression is evaluated as soon as it is bound to a variable, argument to a function etc., Lazy evaluation is completely opposite to eager evaluation, where expression is evaluated when it is required.

For example,
let fun x y = x

Above function returns the value of x, it don’t depend on the value y. No point in evaluating the second argument. In case of eager evaluation strategy, both arguments x and y are evaluated, before calling the function. But lazy programming evaluates the value only when it is required, so it don’t evaluate the second argument at all in this case.
Prelude> let fun x y = x
Prelude> 
Prelude> fun 10 20
10
Prelude> fun 10 [1..]
10
Prelude> fun 10 (2^123456789)
10
Prelude> 


Observe above snippet,
fun 10 [1..] : Second argument is infinite list, eager programming languages end up in calculating the infinite list, where as lazy programs return first argument and exit.

fun 10 (2^123456789) : Second argument is 2^123456789, eager programming languages calculate the value 2^123456789 even though it is not required, where as lazy programs return first argument and exit.

b. One advantage of eager evaluation is that it eliminates the need to track and schedule the evaluation of expressions. Where as lazy evaluation needs to maintain track of the expressions. Haskell keep track of the expressions using thunk. I explained about this in my previous post “How Lazy evaluation works in Haskell”.

What is thunk?
Thunk represents a value that yet to be evauated. Haskell don’t evaluate thunk unless it has to.
Prelude> let fun x y = x
Prelude> fun 10 [1..]
10


In above case thunk represents [1..], since it is not used any where, Haskell don’t evaluate this infinite list.

Problem with thunks
If you keep building complex expressions to solve later, it keeps on consuming memory, obviously affects performance and you may end up in memory overflow error.
foldl (+) 0 [1, 2, 3, 4]
==> foldl (+) (0 + 1) [2, 3, 4]
==> foldl (+) ((0 + 1) + 2) [3, 4]
==> foldl (+) (((0 + 1) + 2) + 3) [4]
==> foldl (+) ((((0 + 1) + 2) + 3) + 4) []
==> (((0 + 1) + 2) + 3) + 4
==> ((1 + 2) + 3) + 4
==> (3 + 3) + 4
==> 6 + 4
==> 10


Explicit strictness
To solve above kind of problems, Haskell provides a way to enforce strict evaluation on expressions, instead of maintaining long thunk.

By using bang(!) operator, we can make an argument strict explicitly.

 For example, let me try to show you the memory consumption of a program which calculates the sum of elements of a list.

Without Bang pattern
listUtil.hs
sumList :: [Integer] -> Integer
sumList xs = sumOfEle xs 0

sumOfEle :: [Integer] -> Integer -> Integer
sumOfEle [] acc = acc
sumOfEle (x:xs) acc = sumOfEle xs (acc+x)

main = print (sumList [1..1000000])


Following commands are used to calculate the memory usage of above program.

ghc listUtil.hs -rtsopts
./listUtil +RTS -s -h -i0.001
$  ghc listUtil.hs -rtsopts
[1 of 1] Compiling Main             ( listUtil.hs, listUtil.o )
Linking listUtil ...
$ ./listUtil +RTS -s -h -i0.001
500000500000
     161,344,208 bytes allocated in the heap
   1,533,989,880 bytes copied during GC
      65,033,816 bytes maximum residency (54 sample(s))
         776,072 bytes maximum slop
              98 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0       266 colls,     0 par    0.090s   0.094s     0.0004s    0.0010s
  Gen  1        54 colls,     0 par    2.510s   2.587s     0.0479s    0.1063s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time    0.049s  (  0.053s elapsed)
  GC      time    2.600s  (  2.681s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    2.650s  (  2.734s elapsed)

  %GC     time      98.1%  (98.0% elapsed)

  Alloc rate    3,264,689,261 bytes per MUT second

  Productivity   1.9% of total user, 1.8% of total elapsed


Now update the program using bangpattern, and rerun the profiling.

listUtil.hs
{-# LANGUAGE BangPatterns #-}
sumList :: [Integer] -> Integer
sumList xs = sumOfEle xs 0

sumOfEle :: [Integer] -> Integer -> Integer
sumOfEle [] acc = acc
sumOfEle (x:xs) !acc = sumOfEle xs (acc+x)

main = print (sumList [1..1000000])


Re run profiling again.
$ ./listUtil +RTS -s -h -i0.001
500000500000
     128,051,920 bytes allocated in the heap
         157,128 bytes copied during GC
          44,312 bytes maximum residency (34 sample(s))
          21,224 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0       213 colls,     0 par    0.000s   0.000s     0.0000s    0.0000s
  Gen  1        34 colls,     0 par    0.002s   0.005s     0.0002s    0.0035s

  INIT    time    0.000s  (  0.001s elapsed)
  MUT     time    0.029s  (  0.032s elapsed)
  GC      time    0.002s  (  0.006s elapsed)
  EXIT    time    0.000s  (  0.000s elapsed)
  Total   time    0.032s  (  0.038s elapsed)

  %GC     time       6.2%  (15.4% elapsed)

  Alloc rate    4,342,656,763 bytes per MUT second

  Productivity  93.5% of total user, 79.7% of total elapsed


Following table summarizes the memory usage.

Name
With out Bang pattern
With Bang pattern
Bytes allocated in the heap
161,344,208
128,051,920
Bytes copied during GC
1,533,989,880
157,128
Bytes maximum residency
65,033,816
44,312
Bytes maximum slop
776,072
21,224
Total memory in use
98 MB
1 MB




Previous                                                 Next                                                 Home

Is Haskell a purely lazy language?


Answer is no.
a. Haskell is not a pure lazy language. For example, pattern matching is usually strict, So trying a pattern match forces evaluation to happen at least far enough to accept or reject the match.
Prelude> let get ('a' : 'b' : xs) = "Hello Krishna"
Prelude> 
Prelude> get "abHello"
"Hello Krishna"
Prelude> 
Prelude> get "xyHello"
"*** Exception: <interactive>:6:5-42: Non-exhaustive patterns in function get


Observe above example, I defined a get method which takes a pattern and return "Hello Krishna", whatever the pattern it simply return string "Hello Krishna".

Observe above example, I defined a get method which takes a pattern and return "Hello Krishna", whatever the pattern it simply return string "Hello Krishna".

get ('a' : 'b' : xs) = "Hello Krishna"


If Haskell is purely lazy language, it shouldn’t evaluate the pattern, since I am not using it anywhere. By when I gave wrong pattern, Haskell throws an error.

Prelude> get "xyHello"
"*** Exception: <interactive>:6:5-42: Non-exhaustive patterns in function get

b. Programmers can also use the seq primitive to force an expression to evaluate regardless of whether the result will ever be used.

c. By using Bang pattern we can ask Haskell to do eager evaluation of expressions.

listUtil.hs
{-# LANGUAGE BangPatterns #-}
sumList :: [Integer] -> Integer
sumList xs = sumOfEle xs 0

sumOfEle :: [Integer] -> Integer -> Integer
sumOfEle [] acc = acc
sumOfEle (x:xs) !acc = sumOfEle xs (acc+x)

main = print (sumList [1..1000000])


{-# LANGUAGE BangPatterns #-}
Above statement enables Bang pattern and ‘!acc’ enforce Haskell to evaluate this expression eagerly.


 
Previous                                                 Next                                                 Home

Haskell: Problems with Lazy evaluation


One problem with lazy evaluation is, it creates many thunks while processing data, which leads to occupy more and more memory so that the operating system has to paginate, which makes the program slower.

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

Prelude> :load Fib.hs
[1 of 1] Compiling Main             ( Fib.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> fibonacci 0
0
*Main> fibonacci 1
1
*Main> fibonacci 2
1
*Main> fibonacci 3
2
*Main> fibonacci 4
3
*Main> fibonacci 5
5


One problem with above program, due to the lazy evaluation of Haskell, it will not evaluate expression unless needed, so these expressions kept in memory. This overhead affects the performance. Try to calculate Fibonacci series for numbers 20, 30, 40 you can observe it.
*Main> fibonacci 20
6765
*Main> fibonacci 30
832040
*Main> fibonacci 40
102334155


One way to solve above problem is by using bang patter (!). Update above program like below using bang pattern.

Fib.hs
{-# LANGUAGE BangPatterns #-}

fibonacci :: Integer -> Integer
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibhelper n 0 1

-- Everything with a ! before it will be evaluated before the function body
fibhelper :: (Integral a) => a -> a -> a -> a
fibhelper 1 _ (!y) = y
fibhelper (!n) (!x) (!y) = fibhelper (n-1) y (x+y)


*Main> fibonacci 20

6765

*Main> fibonacci 30

832040

*Main> fibonacci 40

102334155

*Main> fibonacci 100

354224848179261915075

*Main> fibonacci 1000

43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
I had written more about this in my previous post “How Lazy evaluation works in Haskell”.


Previous                                                 Next                                                 Home