1

I want to define a function fun, a function funResult such and a function HowManyTimesHasBeenRunning such that

In[1]:= fun[]
Out[1]= result1

In[2]:= fun[]
Out[2]= result2

In[3]:= fun[]
Out[3]= result3

In[4]:= funResult
Out[4]= {result1,result2,result3}

In[5]:= HowManyTimesHasBeenRunning 
Out[5]= 3
C. E.
  • 70,533
  • 6
  • 140
  • 264
yode
  • 26,686
  • 4
  • 62
  • 167

2 Answers2

2

Based on linked topic

Module[{i = 0}
  , funResult := fun /@ Range@HowManyTimesHasBeenRunning
  ; HowManyTimesHasBeenRunning := i
  ; fun[] := fun[i] = (++i)^4
];

I'm not appeding to funResult but memoize those results in fun to make it faster when fun is called repeatedly.

Table[fun[], 5]
fun[]
{1, 16, 81, 256, 625}

1296

HowManyTimesHasBeenRunning
6
funResult
{1, 16, 81, 256, 625, 1296}
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • Still confused,because your fun is based on HowManyTimesHasBeenRunning totally.But if my fun is fun[n_]:=N[Tanh[n]].How to make it have that memory function? – yode Mar 02 '17 at 10:08
  • There is no fun[asd_] request in your question. Make sure to include all needed features. – Kuba Mar 02 '17 at 10:13
  • I should add the feature I need or post another question?Sometimes,the implement-method will change the topic a little.I realized that question after I read your answer.I'm feel sorry for that.. – yode Mar 02 '17 at 10:21
  • @yode At this point it is probably better to ask another one. But make sure you have thought everything through before you post. – Kuba Mar 02 '17 at 10:28
2

I would assign UpValues to the symbol fun. See the documentation for TagSet and UpSet, which are interchangeable here:

(* Initialize, UpSet syntax *) 
In[1]:= HowManyTimesHasBeenRunning[fun] ^= 0;
funResult[fun] ^= {};

(* Function definition, TagSet syntax *)
In[3]:= fun[] := (
  fun /: HowManyTimesHasBeenRunning[fun] = 
   HowManyTimesHasBeenRunning[fun] + 1;
  fun /: funResult[fun] = Append[funResult[fun], result1]
  )

In[4]:= fun[]
Out[4]= {result1}

In[5]:= fun[]
Out[5]= {result1, result1}

In[6]:= fun[]
Out[6]= {result1, result1, result1}

In[9]:= HowManyTimesHasBeenRunning[fun]
Out[9]= 3

In[10]:= funResult[fun]
Out[10]= {result1, result1, result1}

By using UpValues, all values are assigned to the symbol fun instead of HowManyTimesHasBeenRunning and funResult, which remain undefined:

In[11]:= Definition[fun]
Out[11]=
funResult[fun]^={result1,result1,result1}
HowManyTimesHasBeenRunning[fun]^=3
fun[]:=(fun/:HowManyTimesHasBeenRunning[fun] = HowManyTimesHasBeenRunning[fun]+1;
fun/:funResult[fun]=Append[funResult[fun],result1])

In[16]:= Defintion[HowManyTimesHasBeenRunning]
Out[16]= Defintion[HowManyTimesHasBeenRunning]

Note that I just wrote result1 every time. You may of course replace that with some actual code.

Theo Tiger
  • 1,273
  • 8
  • 10