1
$\begingroup$
f2[x_, y_] := x^2 + y^3;
g[t_] := {t^2, 3*t+1}

$g$ returns a list, but $f_2$ is a two variable function.
So, we cannot compose these functions:

f2[g[1]]

f1[v_] := v[[1]]^2 + v[[2]]^3
g[t_] := {t^2, 3*t+1}

We can compose these functions like the following:

f1[g[1]]

But I don't want to use a vector variable function like $f_1$.


Any good idea?

$\endgroup$
3
  • 1
    $\begingroup$ Would defining f1[{x_,y_}]:=x^2+y^3 be what you want? $\endgroup$
    – John Doty
    Commented Feb 29, 2020 at 2:15
  • $\begingroup$ @JohnDoty Thank you very much. f1[g[1]] worked. $\endgroup$
    – tchappy ha
    Commented Feb 29, 2020 at 2:20
  • $\begingroup$ Related, possible duplicate: (15749). Also (merely) related: (6588), (13420), (26686) $\endgroup$
    – Mr.Wizard
    Commented Feb 29, 2020 at 2:29

3 Answers 3

3
$\begingroup$

Does this work for you?

ClearAll[f2, g]

f2[{x_, y_}] := f2[x, y]
f2[x_, y_] := x^2 + y^3;
g[t_] := {t^2, 3*t + 1}

f2[g[1]]
65
$\endgroup$
2
  • $\begingroup$ Mr. Wizard, Thank you very much. f2[{x_, y_}] := f2[x, y] is very nice idea. $\endgroup$
    – tchappy ha
    Commented Feb 29, 2020 at 2:22
  • $\begingroup$ @tchappyha Happy to help. See also the Q&A's linked in my comment to your Question for more and related examples. $\endgroup$
    – Mr.Wizard
    Commented Feb 29, 2020 at 2:30
3
$\begingroup$

It looks like you've already got several good answers, but I thought I would mention Apply.

f2[x_, y_] := x^2 + y^3
g[t_] := {t^2, 3 t + 1}
f2@@g[1]

65

The head of the result of evaluating g[1] is List, and Apply replaces this with f2. Essentially, List[1, 4] --> f2[1, 4].

$\endgroup$
1
$\begingroup$

And along the lines of @MassDefect,

f = {#1^2 + #2^3} &
g = {#1^2, 3 #1 + 1} &
f @@ g[1]

Pure functions can be a solution too. Result is {65} as expected.

$\endgroup$

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