Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Map and functional constructs to replace iterative statements

  • To: mathgroup at smc.vnet.net
  • Subject: [mg96863] Re: [mg96783] Map and functional constructs to replace iterative statements
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Thu, 26 Feb 2009 07:57:02 -0500 (EST)
  • References: <200902250900.EAA15513@smc.vnet.net>

On Feb 25, 2009, at 4:00 AM, Andreas wrote:

> I have begun to replace Table, Do, While, or For, but in my  
> thinking with Map, Inner, Outer and other functional programming  
> constructs as I learn more about Mathematica.
>
> But, I'm stuck.  I need to figure out how to use Map (or some  
> related approach) when a function needs both a current value and a  
> previous value in a time series, such as a percentage change  
> function (or perhaps more generally stated, when I need to refer to  
> previous values in a series or even previous calculations).  But  
> first a simple case:
>
> percentChange[currentValue_, previousValue_] := 100 *  
> ( currentValue - previousValue) / previousValue
>
> I know how to apply this iteratively, but how can I do it with Map  
> or some other functional construct?

One option is to use create the pairs of arguments, then apply the  
function

percentChange[#,#2]&@@@Transpose[{Rest[timeSeries],Most[timeSeries]}]

Another option is to do it recursively:

computeChanges[{results_,{previous_,current_}}]:=Append 
[results,percentChange[previous,current]]

computeChanges[{results_,{args__}}]:=computeChanges[{Append 
[results,percentChange[{args}[[2]],{args}[[1]]]],Rest[{args}]}]

computeChanges[timeSeries_]:=computeChanges[{{},timeSeries}]/;VectorQ 
[timeSeries]&&Length[timeSeries]>=2

I realize the recursive solution does not use functional programming  
constructs but I've found that not having to worry about explicit  
indices can result in less bugs.

Regards,

Sseziwa Mukasa


  • Prev by Date: Re: Graphics export for high quality documents
  • Next by Date: Re: Counting Categories
  • Previous by thread: Map and functional constructs to replace iterative statements
  • Next by thread: Re: Map and functional constructs to replace iterative