Re: How to delay action of ...[[i]] (Part[...,i]) until
- To: mathgroup at smc.vnet.net
- Subject: [mg112263] Re: How to delay action of ...[[i]] (Part[...,i]) until
- From: Peter Pein <petsie at dordos.net>
- Date: Tue, 7 Sep 2010 02:01:50 -0400 (EDT)
- References: <i627rm$9c$1@smc.vnet.net>
Am Mon, 6 Sep 2010 08:13:42 +0000 (UTC) schrieb Greylander <greylander at gmail.com>: > Consider the following toy example: > > in> goo[v_] := v.{1, 1}*(3 v) > in> foo[k_][v_] := goo[v] [[k]] > > in> goo[nnn] > out> 3 nnn nnn.{1, 1} > > in>foo[1][{2, 3}] > out>30 > > in> foo[2][nnn] > out>nnn > > Notice how in this last output, because the parameter nnn is > undefined, [[k]] ends up acting on the structure of the expression in > goo, but the intuitive behavior would be for evaluation of [[k]] to > also be delayed. The output I would like to see is: > > in>foo[2][nnn] > out> ( 3 nnn nnn.{1,1} ) [[2]] > in> nnn = {4,5} > % > out> 135 > > But of course it does not happen that way. > > I realize that Mathematica is a specification rather than procedural > language, but surely there is some reasonably elegant way to to delay > the effect of [[2]] above so it acts on the eventual result of > goo[nnn] and not on the structure of the expression. > > This is related to my other questions about using NDSolve on dependent > variables that have arbitrary structure and therefore require some > kind of indexing. > > There must some basic aspect of the Mathematica language that I have > missed which makes indexing and list manipulation more intuitive. (I > hope!) > > Anyone have any insights? > Hi, define your functions in a way that they evaluate only when v is a list of two elements: In[1]:= goo[v:{v1_,v2_}]:=v.{1,1}*(3 v); foo[k_][v:{v1_,v2_}]:=goo[v][[k]]; In[3]:= foo[2][nnn] Out[3]= foo[2][nnn] In[4]:= nnn={4,5}; %% Out[5]= 135 hth, Peter