3
$\begingroup$

I know that I can define a function of a List and get the nth argument like:

f[x_List]:=x[[1]]+x[[2]]

What if the argument of f is not a list? I.e. how to define an equivalent function for

f[x__Integer]:=?

This is probably extremely basic, but I couldn't figure it out from the Slot documentation.

$\endgroup$
0

2 Answers 2

3
$\begingroup$

With f[x__Integer] := ... you can use

{x}[[i]]

to get the ith argument.

$\endgroup$
3
$\begingroup$

Szabolcs's answer (wrapping the sequence x with List and using Part) is the way.

An alternative is to use Indexed

ClearAll[f2]

f2[x__Integer] := Indexed[{x}, 1] + Indexed[{x}, 2]
f2[1, 2, 3, 4, 5]

3

You can also use Slot (#):

ClearAll[f3, f4]

f3[x__Integer] := Slot[1] + Slot[2] &[x]
f3[1, 2, 3, 4, 5]

3

f4[x__Integer] := #1 + #2 &[x]
f4[1, 2, 3, 4, 5]

3

but you can use a pure function directly to define your function:

f5 = #1 + #2 &
$\endgroup$
2
  • $\begingroup$ Thanks. Is the pure function method likely to be faster than the Indexed/List methods? $\endgroup$
    – user366202
    Commented Oct 14, 2019 at 14:24
  • $\begingroup$ @user366202, I am not sure. $\endgroup$
    – kglr
    Commented Oct 14, 2019 at 14:26

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.