       RE: composing functions

• To: mathgroup at smc.vnet.net
• Subject: [mg45533] RE: [mg45527] composing functions
• From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
• Date: Tue, 13 Jan 2004 04:03:50 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```>-----Original Message-----
>From: Pedro L [mailto:pedrito6 at softhome.net]
To: mathgroup at smc.vnet.net
>Sent: Monday, January 12, 2004 8:16 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg45533] [mg45527] composing functions
>
>
>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]
>
>Since  it's  for a real program, I had to do it in "any" way. So I did
>it as I show below:
>
>
>In:= kk = {{f, g, h}, {a, b, c, d}}
>
>Out= {{f, g, h}, {a, b, c, d}}
>
>In:= result1 = {kk[[2,1]]}; For[i = 1, i < Length[kk[]],
>i++, AppendTo[result1, kk[[1,i]]];
>            AppendTo[result1, kk[[2,i + 1]]]]; result1
>
>Out= {a, f, b, g, c, h, d}
>
>In:= result2 = StringJoin @@ ToString /@ result1
>
>Out= afbgchd
>
>In:= result3 = StringInsert[result2, "~", Range[2,
>StringLength[result2]]]
>
>Out= a~f~b~g~c~h~d
>
>In:= result4 = ToExpression[result3]
>
>Out= h[g[f[a, b], c], d]
>
>
>
>
>But I'm really sure that it can be done much better.
>
>Could you help me?
>
>
>

Pedrito,

program recursively,

In:= Clear[composeLeft]

In:= composeLeft[{}, x_, {}] := x  (* terminating condition *)

In:= composeLeft[{}, _, _List] := Message[composeLeft::"nofun"]
In:= composeLeft[_List, _, {}] := Message[composeLeft::"noarg"]
(two error cases, you must define the message texts before use)

The recursive function:
In:=
composeLeft[ff_List, x_, xx_List] :=
composeLeft[Rest[ff], First[ff][x, First[xx]], Rest[xx]]

In:= composeLeft[{f, g, h}, a, {b, c, d}]
Out= h[g[f[a, b], c], d]

A (not so pleasant) alternative using Fold:

In:= Clear[composeLeft]

In:=
composeLeft[ff_List, x_, xx_List] :=
Block[{funList = ff, cf},
cf[r_, s_] := First[{First[funList][r, s], funList = Rest[funList]}];
Fold[cf, x, xx]]

In:= composeLeft[{f, g, h}, a, {b, c, d}]
Out= h[g[f[a, b], c], d]

(Of course, then you should also treat the errors.)

Another idea would be to exploit Composition, just to sketch:

In:= Attributes[cc] = HoldRest;
In:= cc[f_, y_][x_] := f[x, y]

In:=
(Composition @@ MapThread[cc, {{h, g, f}, {d, c, b}}])[a]
Out= h[g[f[a, b], c], d]

--
Hartmut Wolf

```

• Prev by Date: Re: Transpose matrix does not work when MatrixForm is used, why?
• Next by Date: Re: MultiLine Formula (formatting w/brace)
• Previous by thread: Re: composing functions
• Next by thread: Re: composing functions