Re: composing functions

• To: mathgroup at smc.vnet.net
• Subject: [mg45542] Re: [mg45527] composing functions
• From: "Sseziwa Mukasa,,(978) 536-2359" <mukasa at jeol.com>
• Date: Tue, 13 Jan 2004 04:03:56 -0500 (EST)
• References: <200401120715.CAA29367@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```On Jan 12, 2004, at 2:15 AM, Pedro L wrote:

> Hi!
>
> I  would  like  to find a way for composing a list of functions over a
> list of numbers.
>
> I  have  the  list  {{f,  g,  h},  {a,  b, c, d}}
> (f, g, h are functions and a, b, c, d are numbers)
> I would like to obtain h[g[f[a, b], c], d]
>
> [deleted]
>
> Could you help me?
>

As usual there are multiple approaches, you may want to consider the
Composition function.  Here's my approach using Fold.

Placing the elements of the second part of the list in the appropriate
place is trivial:

1) Fold[List,a,{b,c,d}]

results in

{{{a, b}, c}, d}

2) Apply can be used to put the correct head at the correct level, for
example:

Apply[f,Fold[List,a,{b,c,d}],{2}]

results in

{{f[a, b], c}, d}

3) Using the result from 2 and Fold again we can write

Fold[Apply[#2[[1]], #1, {#2[[2]]}] &, Fold[List,
a, {b, c, d}], {{h, 0}, {g, 1}, {f, 2}}]

to get

h[g[f[a, b], c], d]

where we annotate the function heads with the level we want to apply
them at.

To make the general case, for input in the form of a nested list of two
levels, the first of which is the list of heads of functions and the
second is the list of arguments:

lst = {heads}}, Fold[Apply[#2[[1]], #1, {#2[[2]]}] &, Fold[List,
First[
Unevaluated[args]], Rest[{args}]], Transpose[{lst,
Range[Length[lst] -
1, 0, -1]}]]] /;

which results in

In[57]:=
compose[{{f,g,h},{a,b,c,d}}]

Out[57]=
h[g[f[a,b],c],d]

I took the liberty of doing some argument checking, and using sequence
objects.  I'm not sure if using the sequence objects results in an
optimal expression or not, but unless your level of nesting is high it
shouldn't matter.

Regards,

Ssezi

```

• Prev by Date: Re: composing functions
• Next by Date: Re: Transpose matrix does not work when MatrixForm is used, why?
• Previous by thread: Re: composing functions
• Next by thread: Re: composing functions