       Re: functional programming excercise from Mastering Mathematica

• To: mathgroup at smc.vnet.net
• Subject: [mg55280] Re: [mg55212] functional programming excercise from Mastering Mathematica
• From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
• Date: Fri, 18 Mar 2005 05:33:56 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```>-----Original Message-----
>From: Torsten Coym [mailto:torsten.coym at eas.iis.fraunhofer.de]
To: mathgroup at smc.vnet.net
>Sent: Thursday, March 17, 2005 9:29 AM
>Subject: [mg55280] [mg55212] functional programming excercise from
>Mastering Mathematica
>
>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,
>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
>
>

Torsten,
as...

In:= FoldList[f, x, {a1, a2, a3, a4}]
Out=
{x, f[x, a1], f[f[x, a1], a2], f[f[f[x, a1], a2], a3],
f[f[f[f[x, a1], a2], a3], a4]}

...is

In:=
ComposeList[{f[#, a1] &, f[#, a2] &, f[#, a3] &, f[#, a4] &}, x]
Out=
{x, f[x, a1], f[f[x, a1], a2], f[f[f[x, a1], a2], a3],
f[f[f[f[x, a1], a2], a3], a4]}

we just have to build the first element in ComposeList from f and {a1,
a2, a3, a4}.

Several ways exist, e.g.

In:= Function[e, f[#, e] &] /@ {a1, a2, a3, a4}
Out=
{f[#1, a1] &, f[#1, a2] &, f[#1, a3] &, f[#1, a4] &}

In:= Function[z, f[z, #]] & /@ {a1, a2, a3, a4}
Out=
{Function[z, f[z, a1]], Function[z, f[z, a2]], Function[z, f[z, a3]],
Function[z, f[z, a4]]}

In:= Function /@ Thread[f[#, {a1, a2, a3, a4}]]
Out=
{f[#1, a1] &, f[#1, a2] &, f[#1, a3] &, f[#1, a4] &}

In:=
Thread[Unevaluated[Composition[Function, f][#, {a1, a2, a3, a4}]]]
Out=
{f[#1, a1] &, f[#1, a2] &, f[#1, a3] &, f[#1, a4] &}

--
Hartmut Wolf

```

• Prev by Date: Normal Disappear Problem
• Next by Date: Re: Combination
• Previous by thread: Re: functional programming excercise from Mastering Mathematica
• Next by thread: Re: functional programming excercise from Mastering Mathematica