MathGroup Archive 2005

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

Search the Archive

Re: functional programming excercise from Mastering Mathematica

  • To: mathgroup at smc.vnet.net
  • Subject: [mg55290] Re: functional programming excercise from Mastering Mathematica
  • From: Peter Pein <petsie at arcor.de>
  • Date: Fri, 18 Mar 2005 05:34:18 -0500 (EST)
  • References: <d1bflp$lja$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Torsten Coym wrote:
> I'm quite new to Mathematica and its functional programming capabilities 
> so I did some reading in John Gray's "Mastering Mathematica". There is 
> an excercise in chapter 6 as follows
> 
> Write your own function composeList that works just like the built-in 
> operation with the same name, using FoldList. Conversely, write your own 
> function foldList that works just like the built-in operation with the 
> same name, using ComposeList.
> 
> Unfortunately, there is no solution given at the end of the book (or I 
> didn't find it). I could figure out a way to do the first task:
> 
> composeList[funlist_List, var_] := FoldList[(#2[#1]) &, var, funlist]
> 
> but I can't manage the second task...
> 
> I know it's rather academic, but ... any help is welcome!
> 
> Torsten
> 
foldList[f_, x_, {}] := {x};
foldList[f_, x_, lst_List] :=
     {x, Sequence @@ foldList[f, f[x, First[lst]], Rest[lst]]};

foldList[f, x, {a, b, c}] == FoldList[f, x, {a, b, c}]

==> True

If you need to handle large Lists (length > 250), you'll reach the
recursion limit.
You could try the procedural approach

Clear@foldList;
foldList[f_, x_, lst_] :=
  Module[{n = Length[lst], r},
    For[i = 1; r = Table[x, {n + 1}], i <= n, i++,
      r[[i + 1]] = f[ r[[i]], lst[[i]] ]
    ];
  r];

or even better the builtin FoldList ;-)
-- 
Peter Pein
Berlin


  • Prev by Date: Re: Re: Sum
  • Next by Date: Re: functional programming excercise from Mastering Mathematica
  • Previous by thread: Re: functional programming excercise from Mastering Mathematica
  • Next by thread: Re: functional programming excercise from Mastering Mathematica