Group Abstract Group Abstract

Message Boards Message Boards

0
|
2.2K Views
|
5 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Is there any construct similar to function pointers?

Posted 1 year ago

Hi, in my MATHEMATICA program I need to have a number of functions, say:

fun1[x_]:=function code 1;
fun2[x_]:=function code 2;
fun3[x_]:=function code 3;

and a further code that intensively uses one of these functions, but the choice which function is to be used depends on the input parameter selected by the program user. Is there any MATHEMATICA language construct, similar to "C" pointers to functions, which allows one to avoid rewriting several versions of the code (for every function separately) or frantically check the user parameter at every call of the function, to decide which function is to be used? Or, is there any other recommended way to handle the above situation? Lesław

POSTED BY: Leslaw Bieniasz
5 Replies
POSTED BY: Leslaw Bieniasz
Posted 1 year ago
POSTED BY: Eric Rimbey

Another way using Association

fun1[x_] := x;
fun2[x_] := x^2;
fun3[x_] := x^3;

functions = <|1 -> fun1, 2 -> fun2, 3 -> fun3|>;

functions[3][5]
(* 125 *)
POSTED BY: Rohit Namjoshi
Posted 1 year ago

In Mathematica, everything is an expression. So, the expression fun1 is effectively the "function pointer" that you want. It's an expression with down values that specify how to evaluate when applied to arguments. Let's make this concrete:

fun1[x_Integer] := ToString[StringForm["fun1 accepts `` and doubles: ``", x, 2 x]];
fun2[x_Integer] := ToString[StringForm["fun2 accepts `` and squares: ``", x, x^2]];
fun3[x_Integer] := ToString[StringForm["fun3 accepts `` and factors: ``", x, FactorInteger[x]]];

Let's simulate the user's choice with a random choice:

chosenFunc = RandomChoice[{fun1, fun2, fun3}];

Now let's use our choice:

chosenFunc[18]
(* "fun2 accepts 18 and squares: 324" *)
POSTED BY: Eric Rimbey
Posted 1 year ago

Could the following be an alternative?

Definitions:

fun[1]=Function[#+5];
fun[2]=Function[(#+6)^2];
fun[3]=Function[(#+7)^3];
fun[index_,argument_]:=fun[index][argument]

Use:

fun[1,7]
fun[2,7]
fun[3,7]

(* 12   *)
(* 169  *)
(* 2744 *)
POSTED BY: Hans Milton
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard