Piotr Wera
Piotr Wera

Reputation: 49

Strings form list to function

I am using Mathematica version 5.2. I need to split it to function, and make a result.. I've created this monster:

mx = {};
arg = {};
fun = {}; 
x =. 
y =.

here are lists and arguments

switchfunction2[y_] := Switch[y,
  1, AppendTo[fun, Cos[Random[Integer, {1, 10}]]],
  2, AppendTo[fun, Sin[Random[Integer, {1, 10}]]],
  3, AppendTo[fun, Tan[Random[Integer, {1, 10}]]],
  4, AppendTo[fun, Csc[Random[Integer, {1, 10}]]],
  5, AppendTo[fun, Sec[Random[Integer, {1, 10}]]],
  6, AppendTo[fun, Cot[Random[Integer, {1, 10}]]]
]

and random functions

Do[AppendTo[mx, Random[Integer, {1, 10}]], {i, 2}] 

mx[[1]] " has been chosed"
mx[[2]] "argumments "
Do[AppendTo[arg, Random[Integer, {1, 5}]], {i, mx[[2]]}] 
arg
Do[switchfunction2 /@ {arg[[i]]}, {i, mx[[2]]}]
fun

I want to obtain f[z_]:=fun[[1]]+fun[[2]]...

Upvotes: 1

Views: 190

Answers (1)

Heike
Heike

Reputation: 24420

In this case, I would do something like

mx = RandomInteger[{1, 10}, 2];
arg = RandomInteger[{1, 5}, mx[[2]]];

switch[y_] := Module[{f},
  f = Switch[y, 1, Cos, 2, Sin, 3, Tan, 4, Csc, 5, Sec, 6, Cot];
  f[RandomInteger[{1, 10}]]]

fun = switch /@ arg;

Total[fun]

Or without using a switch function:

mx = RandomInteger[{1, 10}, 2]
flist = RandomChoice[{Cos, Sin, Tan, Csc, Sec, Cot}, mx[[2]]];

fun = #[RandomInteger[{1, 10}]] & /@ flist;
Total[fun]

Edit

Here's a version that should work in Mathematica 5.2.

mx = Table[Random[Integer, {1, 10}], {2}];
arg = Table[Random[Integer, {1, 5}], {mx[[2]]}];

switch[y_] := Module[{f}, 
  f = Switch[y, 1, Cos, 2, Sin, 3, Tan, 4, Csc, 5, Sec, 6, Cot];
  f[Random[Integer, {1, 10}]]]

fun = switch /@ arg;

Total[fun]

To make a function out of this you could wrap everything in a Module, e.g.

f := Module[{mx, arg, switch},
  mx = Random[Integer, {1, 10}];
  arg = Table[Random[Integer, {1, 5}], {mx}];
  switch[y_] := Module[{f}, 
    f = Switch[y, 1, Cos, 2, Sin, 3, Tan, 4, Csc, 5, Sec, 6, Cot];
    f[Random[Integer, {1, 10}]]];
  Total[switch /@ arg]]

Upvotes: 4

Related Questions