Message Boards Message Boards

0
|
2468 Views
|
5 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Which[] calling Main Evaluate - can this be avoided?

Would not seem that Which[] would be a problem in compiling functions, but it's doing a call to Main Evaluate - its obviously on the list of compiled functions and pretty basic. Running the simple code below illustrates it (in v13.1). Its does not happen with If[] as one would expect. Really like to use Which[], but can a call to Main Evaluate be avoided?
Thanks in advance.

<< CompiledFunctionTools`;
fun = Compile[{{k, _Integer}, {u, _Real}}, 
   Which[k == 1, u + 1, k == 2, u + 4]];
funIf = Compile[{{k, _Integer}, {u, _Real}}, If[k == 1, u + 1, u + 4]];
fun[1, 2]
funIf[1, 2]
CompilePrint[funIf]
CompilePrint[fun]

For Which [] the  result without the header is
I0 = A1
R0 = A2
Result = R1
R1=MainEvaluate[Function[{k,u},Which[k==1,u+1,k==2,u+4]][I0,R0]]
Return

and for IF the result without the header is
I0 = A1
R0 = A2
I2 = 4
I1 = 1
Result = R1
B0=I0==I1
2 if[!B0] goto 7
3 R1=I1
4 R2=R0+R1
5 R1=R2
6 goto 10
7 R1=I2
8 R3=R0+R1
9 R1=R3
10  Return
POSTED BY: Neal Maroney
5 Replies
Posted 1 year ago

Yes, this would work I believe because the compiler has a default value of 0.0 for f, which it can return when k is not 1 or 5.

POSTED BY: Asim Ansari

Am update.
The following also works correctly.

fun= Compile[{{k, _Integer}, {u, _Real}},   Block[{f = 0.0`},    
Which[k == 1 , f = u + 1, k == 5 , f = u + 2 ];
f  ]];
POSTED BY: Neal Maroney

Thanks. Thought you just made and if out of which but it seems to work for additional arguments say

fun = Compile[{{k, _Integer}, {u, _Real}}, 
   Which[k == 1, u + 1, k == 2, u + 3, True, u + 4]];

but anything higher than 2 will default to u+4 so have to watch that . Placing False there will result in main evaluate.
Wondering why the strange behavior . thanks again

POSTED BY: Neal Maroney
Posted 1 year ago

You can change your function to

    fun = Compile[{{k, _Integer}, {u, _Real}}, 
     Which[k == 1, u + 1, True, u + 4]
    ];
POSTED BY: Asim Ansari
Posted 1 year ago

You can change your function to

    fun = Compile[{{k, _Integer}, {u, _Real}}, 
     Which[k == 1, u + 1, True, u + 4]
    ];
POSTED BY: Asim Ansari
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract