# Constructing a function that returns two distinct values by Mathematica

I'm trying to enter a function in Mathematica that can take two inputs, a, and b, and return two outcomes based on those two numbers.

I will assume the name of this function as

Resultsf[a _,b _]

the inputs are :

x1=a; x2=b;

The two operations which I would like Mathematica to do are :

f1=x1+x2; f2=x1*x2;

Here are the two results that I anticipated from the function Resultsf[a _,b _]

input Resultsf[3,3] output 6

   9


what is the sequence of such kind of program? Regards

• You can use List or {} to return multiple values. In your case it would be Resultsf[a_, b_] := {a+b, a*b}. Dec 28, 2022 at 5:51
• As @BenIzd said, return a list, then you can display the list in any desired manner. For example, Results[3, 3] // Column or {Results[3, 3]} // Grid Dec 28, 2022 at 6:15

Using Apply and Function:

Resultsf[{a_, b_}] := Apply[Function[{x, y}, {x + y, x*y}], {a, b}]


Test using Syed's example:

Resultsf[#] & /@ {{-4, -1}, {-5, 2}, {-5, -5}, {3, 1}, {-5, -1}}
(*{{-5, 4}, {-3, -10}, {-10, 25}, {4, 3}, {-6, 5}}*)


The fundamental data structure in Mathematica is the List. If you want to put two things together, you put them into a list. So, Resultsf should probably return a list:

Resultsf[a_, b_] := {f1[a, b], f2[a, b]}


Try it out:

Resultsf[x, y]


{f1[x, y], f2[x, y]}

That's probably the easiest to understand way to do it. But there is a bit of repetition, specifically we had to "mention" a and b twice each. Mathematica has a built in function to deal with exactly this situation: multiple functions applied to the same arguments. It's called Through:

AlternateResultsf[a_, b_] := Through[{f1, f2}[a, b]]


Try this one out:

AlternateResultsf[x, y]


{f1[x, y], f2[x, y]}

To make this concrete, we'll use the multiplication and addition that you gave in your example:

AlternateResultsf[a_, b_] := Through[{Plus, Times}[a, b]]


And giving it a go:

AlternateResultsf[x, y]


{x + y, x y}

Or, going back to the first implementation:

Resultsf[a_, b_] := {a + b, a*b}


And now we have

Resultsf[x, y]


{x + y, x y}

Clear[alist]
SeedRandom[1];

alist = RandomInteger[{-5, 5}, {5, 2}]


{{-4, -1}, {-5, 2}, {-5, -5}, {3, 1}, {-5, -1}}

Through[{Plus, Times}[Sequence @@ #]] & /@ alist


OR

{Plus @@ #, Times @@ #} & /@ alist


Result:

{{-5, 4}, {-3, -10}, {-10, 25}, {4, 3}, {-6, 5}}

Using Query :

list = {{-4, -1}, {-5, 2}, {-5, -5}, {3, 1}, {-5, -1}};

Query[All, Apply /@ {Plus, Times}] @ list


{{-5, 4}, {-3, -10}, {-10, 25}, {4, 3}, {-6, 5}}