haskell expression evaluation -


i new haskell , give me suggestion following haskell expression evaluation.

f xs = foldr (\x n->n+1) 0 xs 

function

f [1, 4] 

evaluation

(\x n->n+1) 1 (foldr  (\x n->n+1) 0 [4]) = (foldr  (\x n->n+1) 0 [4]) + 1 = ((\x n->n+1) 4 (foldr  (\x n->n+1) 0 [4])) + 1 = (foldr  (\x n->n+1) 0 [] + 1) + 1 = (0 + 1) + 1  = 1 + 1 = 2 

first of need foldr implementation:

foldr f z []     = z  foldr f z (x:xs) = f x (foldr f z xs) 

now let's try "trace" our computation f [1, 4]:

f [1, 4]  -- rewrite list  f (1:(4:[]))  -- replace f function xs = (1:(4:[])) foldr (\x n-> (+) n 1 ) 0 (1:(4:[]))   -- using foldr f z (x:xs) = f x (foldr f z xs) -- f = (\x n -> (+) n 1), z = 0, x = 1, xs = (4:[]) (\x n ->(+) n 1) 1 ( foldr (\x n -> (+) n 1) 0 (4:[]))  -- lambda function evaluated x = 1, n = ( foldr (\x n -> n+1) 0 (4:[])) (+) (foldr (\x n -> n+1) 0 (4:[])) 1  -- (+) try evaluate first parameter -- foldr applied f = (\x n -> (+) n 1), z = 0,  x = 4, xs = [] (+) ((\x n -> (+) n 1) 4 (foldr (\x n -> (+) n 1) 0 [] )) 1  -- again lambda evaluated x = 4 , n = (foldr (\x n -> (+) n 1) 0 [] )  (+) ( (+) (foldr (\x n -> (+) n 1) 0 [] ) 1 ) 1  --  foldr evaluated again time first form used, z counts: f = (\x n -> (+) n 1), z = 0, [] = [] (+) ( (+) ( 0 ) 1 ) 1  -- go flow (+) ( (+) 0 1 ) 1 (+) ( 1 ) 1 (+) 1 1 2 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -