Group Abstract Group Abstract

Message Boards Message Boards

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

Is there any construct similar to function pointers?

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

I think this is cleaner:

chosenFun =
 Switch[
  param,
  1, fun1,
  2, fun2,
  3, fun3,
  _, Null]

You would do something more appropriate than just Null in the fall-through case. If, Switch, and Which are special forms that hold their arguments unevaluated, so you don't need to worry about unexpected evaluation as a side-effect.

But, another way to view this is as a parameterization to your function, like Hans suggested. An alternate way to do that would be:

newFun[1] = fun1;
newFun[2] = fun2;
newFun[3] = fun3;

And now you can just use:

newFun[param][x]
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
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