Haskell Pattern Matching: Readability and Performance -


i'm going through learn haskell tutorial , i've been tripping on of examples author has given.

for example reimplemented zip follows:

zip' :: [a] -> [b] -> [(a,b)]   zip' _ [] = []   zip' [] _ = []   zip' (x:xs) (y:ys) = (x,y):zip' xs ys 

he uses similar approach other examples, puts specific patterns first. here different version of zip function:

zip' :: [a] -> [b] -> [(a,b)] zip' (x:xs) (y:ys)  = (x, y):zip' xs ys zip' _ _            = [] 

as far understand both methods same thing. if empty list provided either way (x:xs) or (y:ys) won't match finish recursion appending empty list [].

  1. i prefer second version readability, maybe i'm wrong in doing so.
  2. does have effect on performance of method? far understand if top pattern not match, haskell check against next pattern. order of patterns affect performance?

kind regards,

edit:

possibly duplicate of: haskell ghc: time complexity of pattern match n constructors?

summary: order of patterns important semantics (in terms of strict evaluation of arguments) , readability of function. pattern match in o(1) time complexity.

as far understand both methods same thing.

almost; exception:

\> zip' undefined []   -- 1st definition of zip' [] \> zip' (filter (< 4) [1..]) [1, 2, 3] [(1,1),(2,2),(3,3)] 

whereas:

\> zip' undefined []   -- 2nd definition of zip' *** exception: prelude.undefined \> zip' (filter (< 4) [1..]) [1, 2, 3] [(1,1),(2,2),(3,3)   -- gets stuck here; never returns 

in other words, 2nd definition forces weak head normal form both arguments.

performance-wise, means 1 can construct pathological example such whnf involves heavy computations, therefore 1 definition performs differently other.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -