|
[Date Index]
[Thread Index]
[Author Index]
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[1]:= kk = {{f, g, h}, {a, b, c, d}}
>
>Out[1]= {{f, g, h}, {a, b, c, d}}
>
>In[2]:= result1 = {kk[[2,1]]}; For[i = 1, i < Length[kk[[2]]],
>i++, AppendTo[result1, kk[[1,i]]];
> AppendTo[result1, kk[[2,i + 1]]]]; result1
>
>Out[2]= {a, f, b, g, c, h, d}
>
>In[3]:= result2 = StringJoin @@ ToString /@ result1
>
>Out[3]= afbgchd
>
>In[4]:= result3 = StringInsert[result2, "~", Range[2,
>StringLength[result2]]]
>
>Out[4]= a~f~b~g~c~h~d
>
>In[5]:= result4 = ToExpression[result3]
>
>Out[5]= 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[15]:= Clear[composeLeft]
In[16]:= composeLeft[{}, x_, {}] := x (* terminating condition *)
In[17]:= composeLeft[{}, _, _List] := Message[composeLeft::"nofun"]
In[18]:= composeLeft[_List, _, {}] := Message[composeLeft::"noarg"]
(two error cases, you must define the message texts before use)
The recursive function:
In[19]:=
composeLeft[ff_List, x_, xx_List] :=
composeLeft[Rest[ff], First[ff][x, First[xx]], Rest[xx]]
In[20]:= composeLeft[{f, g, h}, a, {b, c, d}]
Out[20]= h[g[f[a, b], c], d]
A (not so pleasant) alternative using Fold:
In[65]:= Clear[composeLeft]
In[66]:=
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[68]:= composeLeft[{f, g, h}, a, {b, c, d}]
Out[68]= 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[81]:= Attributes[cc] = HoldRest;
In[82]:= cc[f_, y_][x_] := f[x, y]
In[84]:=
(Composition @@ MapThread[cc, {{h, g, f}, {d, c, b}}])[a]
Out[84]= 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
|