2
$\begingroup$

I have a vector-valued function whose arguments, for some reasons, are forced to be numeric by adding ?NumericQ. I can correctly take a particular element of the vector value of the function if I input specific numberic arguments. For example,

f[x_?NumericQ, y_?NumericQ] := {-x, -y, -y - 1}

f[1, 2]
{-1, -2, -3} (* output *)

f[1, 2][[1]]
-1  (* output *)

So far so good. But sometimes I need to leave the arguments symbolic and specify them by rules. That creates mistakes. For example:

f[x, y][[1]] /. {x -> 1, y -> 2}
1 (* output *)

Mathematica executes Part before applying the rules, which is not what I want. The problem is not solved even if I use Evaluate:

Evaluate[f[x, y]][[1]] /. {x -> 1, y -> 2}
1 (* output *)

Is there a simple built-in function to correct the order (replacing x, y using the rules before evaluating the function and taking part)? Currently I need to define a new module function to take the particular element and then work with the new function. I'm wondering if there is a simpler way. Thank you!

$\endgroup$
1
  • $\begingroup$ Unevaluated[f[x, y][[1]]] /. {x -> 1, y -> 2}? $\endgroup$
    – kglr
    Sep 17, 2021 at 3:45

1 Answer 1

4
$\begingroup$

You can use Indexed for this purpose:

f[x_?NumericQ, y_?NumericQ] := {-x, -y, -y-1}

Indexed[f[x,y],1] /. {x -> 1, y -> 2}

-1

$\endgroup$
1
  • $\begingroup$ Thanks Carl and kglr! Both Unevaluated and Indexed work for my purpose. $\endgroup$
    – Adam
    Sep 17, 2021 at 4:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.