Erlang (programming language)/Tutorials/Folding: Difference between revisions

From Citizendium
Jump to navigation Jump to search
imported>Eric Evers
No edit summary
imported>Eric Evers
No edit summary
Line 4: Line 4:
F is some folding function, S is some starting value, and L  is some List that needs folding. Let us do some simple folding. The following fold calculates the lenght of a list. Here the current list item, _C is ignored, and the accumulator, A, counts the number of elements in the list.
F is some folding function, S is some starting value, and L  is some List that needs folding. Let us do some simple folding. The following fold calculates the lenght of a list. Here the current list item, _C is ignored, and the accumulator, A, counts the number of elements in the list.


   lists:foldr( fun(_C,A)->A+1 end, 0, [1,2,3]).
   1> lists:foldr( fun(_C,A)->A+1 end, 0, [1,2,3]).
   3
   3


We could reverse a list with fold if we like.
We could reverse a list with fold if we like.


   lists:foldr(fun(C,A)->A++[C] end, [], [a,b,c]).  
   2> lists:foldr(fun(C,A)->A++[C] end, [], [a,b,c]).  
   [c,b,a]
   [c,b,a]


Or to get fancy we could try a finite difference.
Or to get fancy we could try a finite difference.


   lists:foldr(
   3> lists:foldr(
     fun(C,{P,A})->{C,[P-C]++A} end,  
     fun(C,{P,A})->{C,[P-C]++A} end,  
     {0,[]},   
     {0,[]},   
     [1,4,9,16]).  
     [1,4,9,16]).


   {1,[3,5,7,-16]}
   {1,[3,5,7,-16]}
In example 3, we used a tuple to remember the previous value so we could use it for next difference. Fold is
a function with a limited attention span. We might like to delete the last item because is has a non-intuitive relation to the source list.

Revision as of 12:52, 13 September 2008

Fun with folding

Fold is a powerful tool, when you get to know it. lists:foldr(F,S,L) takes three arguments: F is some folding function, S is some starting value, and L is some List that needs folding. Let us do some simple folding. The following fold calculates the lenght of a list. Here the current list item, _C is ignored, and the accumulator, A, counts the number of elements in the list.

 1> lists:foldr( fun(_C,A)->A+1 end, 0, [1,2,3]).
 3

We could reverse a list with fold if we like.

 2> lists:foldr(fun(C,A)->A++[C] end, [], [a,b,c]). 
 [c,b,a]

Or to get fancy we could try a finite difference.

 3> lists:foldr(
   fun(C,{P,A})->{C,[P-C]++A} end, 
   {0,[]},   
   [1,4,9,16]).  
 {1,[3,5,7,-16]}

In example 3, we used a tuple to remember the previous value so we could use it for next difference. Fold is a function with a limited attention span. We might like to delete the last item because is has a non-intuitive relation to the source list.