[Haskell-beginners] Saving intermediate calculations

Henk-Jan van Tuyl hjgtuyl at chello.nl
Mon Mar 16 22:55:56 UTC 2015


On Thu, 12 Mar 2015 16:34:19 +0100, Abhinav Kalawatia
<kalawatia_abhinav at yahoo.com> wrote:

> Hi Henk,
> I hope you are well :)
> Thanks for your help with the solution for saving the intermediate  
> calculations. Henk, could you please help me understand the following  
> code snippet?
> ewma1 a (x:xs) = reverse $ foldl' f [x] xs
>     where f m@(x':xs') n = ((a * n) + ((1 - a) * x')):m

You can do mathematical substitution:

ewma1 a (x:xs) = reverse $ foldl' f [x] xs
         where f m@(x':xs') n = ((a * n) + ((1 - a) * x')):m

+ (definition of foldl, which performs the same calculation as foldl',  
though not strict)

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

=> (substitute definition of foldl in ewma1)

ewma1 a (x1:x2:xs) = reverse $ foldl' f (f [x1] x2) xs
         where f m@(x':xs') n = ((a * n) + ((1 - a) * x')):m

=> (substitute f)

ewma1 a (x1:x2:xs) = reverse $ foldl' f (((a * x2) + ((1 - a) * x1)):[x1])  
xs
         where f m@(x':xs') n = ((a * n) + ((1 - a) * x')):m

Repeat the last two steps until the list is processed.

There is a tool to display this automatically: Hat, but I could not get it  
to run properly on my Windows PC.
The homepage is at:
   http://projects.haskell.org/hat/

Regards,
Henk-Jan

-- 
Folding at home
What if you could share your unused computer power to help find a cure? In
just 5 minutes you can join the world's biggest networked computer and get
us closer sooner. Watch the video.
http://folding.stanford.edu/


More information about the Beginners mailing list