1
votes

I'm a bit confused about, how does Return[], returns result from function. For example, take those two functions:

CalcLossTotal = Function[
   {data, units},

   Clear[i];
   Return[Table[
     data[[i, 1]]*units,
     {i, 1, Length[data]}]
    ];
   ]; 

and

CalcPremiums = Function[
   {data, lossTotal},

   Clear[i];
   Return[Table[
     data[[i, 2]]*lossTotal[[i]],
     {i, 1, Length[data]}]
    ];
   ];

wheres CalcPremiums[] depends upon CalcLossTotal[] and data which is same for both of them. Upon calculating LossTotal (e.g. result from CalcLossTotal[]), result returned from it isn't array of data, but

Return[{0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000}]

Is this the way Mathematica works, or there is something that i miss when defining/returning from functions.

Thanks in advance.

2
Have a look here. - Leonid Shifrin

2 Answers

2
votes

The construct you want is this:

CalcPremiums[data_, lossTotal_] := (
  Return[Table[data[[i, 2]]*lossTotal[[i]], {i, 1, Length[data]}]];)

note that return is superflous if you are returning the final result so,

CalcPremiums[data_, lossTotal_] := (
  Table[data[[i, 2]]*lossTotal[[i]], {i, 1, Length[data]}]);

(note no semicolon after Table[] inside the parenthesis) The parenthesis are not needed here either but I left them in assuming you really have a multi line function.

I must say I'm a bit puzzled why your construt returns "return[]". Consider this:

g = Function[u, If[u < 0, Return[u], 0]];
f[x_] := (
    y = g[x] ;
    {x, y})

for x<0 the effect of the pure Function (g) is to Return x from the calling function (f), not to set y=x.

 f[-1]-> -1   , f[1] -> {1,0} 

I see the logic but it's not obvious to me.

0
votes

I'd guess the problem is an effect of Function having the attribute HoldAll.

Your functions will work if rewritten like so:-

CalcLossTotal = Function[
   {data, units},

   Catch[
    Clear[i];
    Throw[Table[
      data[[i, 1]]*units,
      {i, 1, Length[data]}]
     ];
    ]];


CalcPremiums = Function[
   {data, lossTotal},

   Catch[
    Clear[i];
    Throw[Table[
      data[[i, 2]]*lossTotal[[i]],
      {i, 1, Length[data]}]
     ];
    ]];