11
$\begingroup$

The below function when applied to a list of two elements, will output the maximum between the two:

If[#1 > #2, ##] &    

For example:

In[1] : If[#1 > #2, ##] & [22,21]
Out[1]: 22 

In[2] : If[#1 > #2, ##] & [21,22]
Out[2]: 22 

However I don't really get what's the use of the ## here. In the first output, why isn't it return Sequence[22,21] instead? And in the second output, how does the function knows to return 22, when there isn't a return statement for false condition in the If function ?

$\endgroup$
8
$\begingroup$

The answer is simple: First, you really need to look up the documentation of ##. It means "take all arguments". But more importantly, you can use the property that a > b stays unevaluated when neither true or false can be computed. So check this out:

If[#1 > #2, ##] &[a, b]
(* If[a > b, a, b] *)

Do you see how ## converts this construct into a simple "if a>b then a else b"?

Furthermore, Sequence[a,b,c] is Mathematica's way of saying "a sequence of arguments that can be fed into a function". As you might know, it is not possible to evaluate the input a,b,c without error. For normal functions, which don't have the attribute HoldAllComplete, a Sequence[...] expression is always flattened out.

func[Sequence[a, b, c]]
(* func[a, b, c] *)

This is exactly what happened in your If. When you understand that

## &[22, 21]
(* Sequence[22, 21] *)

and you know it's turned into a real sequence (without the Sequence around it) when inside a function, you understand what happened in your case.

$\endgroup$
  • 1
    $\begingroup$ Since you explicitly mention HoldAllComplete, it might be worth mentioning SequenceHold as well $\endgroup$ – Lukas Lang Oct 12 at 18:49
6
$\begingroup$

To understand how the SlotSequence (##) works, use Trace

Trace[If[#1 > #2, ##] &[22, 21]]

enter image description here

Trace[If[#1 > #2, ##] &[21, 22]]

enter image description here

$\endgroup$

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.