0
$\begingroup$

I have a doubt regarding function with variable number of arguments.

Let's consider the following case:

a = {{1, 2}, {2, 3}};
b = {{1, 3}, {3, 3}, {4, 1}};
function[x__] := x//Intersection
function[a[[;;,1]], b[[;;,1]]]

In this case everything works nicely, but if I want to select the first column of the data within the function itself mathematica returns an error:

a = {{1, 2}, {2, 3}};
b = {{1, 3}, {3, 3}, {4, 1}};
function[x__] := x[[;;,1]]//Intersection
function[a, b]
Part::pkspec1: The expression {{1,3},{3,3},{4,1}} cannot be used as a part specification.
Part::pkspec1: The expression {{1,2},{2,3}} cannot be used as a part specification.

However, if I apply the function to just one variable it works ok:

function[a]
{1,2}

What am I missing? Why I can't select parts of the variable if I have more than one variable? And which is the correct way of doing it?

Thanks!

$\endgroup$
3
$\begingroup$

x__ makes a Sequence object when it captures more than one argument. Sequence objects automatically expand into separate arguments when they appear in an argument list. So,

f[x__] := x[[1]]
f[a, b]
(* Part::pkspec1: The expression b cannot be used as a part specification. *)
(* a[[b, 1]] *)

One easy way to deconstruct a Sequence is to turn it into a List:

g[x__] := {x}[[1]]
g[a, b]
(* a *)
$\endgroup$
  • $\begingroup$ Thanks for your answer! I now understand why it doesn't accept my notation. However converting the sequence in a list doesn't help me with the Intersection function because it only accepts sequences as argument. How can I solve it? I could convert the list in sequence again, but it is not quite elegant and also it could be problematic because converting strings to sequences does not preserve the nested nature of the original string. $\endgroup$ – Fraccalo Jul 21 '17 at 6:34
  • 1
    $\begingroup$ @Fraccalo Use Apply. Mathematica transforms f@@{a,b} to f[a,b]. $\endgroup$ – John Doty Jul 21 '17 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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