Saturday 30 April 2016

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

No comments:

Post a Comment