11
$\begingroup$

I would prefer to write {_, foo} = LongFunctionName[arg1, arg2] instead of foo = LongFunctionName[arg1, arg2][[2]] or foo = Last @ LongFunctionName[arg1, arg2]. Using an actual name for the throwaway variable makes code unnecessarily verbose and can be misleading/confusing. Is it a good idea to use $ for throwaways?

$\endgroup$
3
  • 3
    $\begingroup$ I don't believe there is a convention. In fact I don't believe this is a common method at all, in Mathematica. This is closely related to (30138) which is probably the one @Kuba was thinking of. $\endgroup$
    – Mr.Wizard
    Commented Mar 9, 2017 at 11:36
  • 2
    $\begingroup$ +1, I would like to see a "throwaway variable" in Mathematica. MATLAB also has it, it uses the tilde. $\endgroup$
    – C. E.
    Commented Mar 9, 2017 at 12:11
  • $\begingroup$ @ZeitPolizei I would like to know if you would object to my closing this question as a duplicate of the one linked above. I feel that this is probably best addressed in a single place, and if there are aspects of your question that are not addressed there it may be better to extend that question rather than creating a separate one. If this action is taken your question will remain as an entry point for searches. $\endgroup$
    – Mr.Wizard
    Commented Mar 9, 2017 at 23:28

2 Answers 2

5
$\begingroup$

Actually you can write {_, foo} = . . . and it works, as noted in How to ignore list elements when extracting with pattern matching.

If one is going to make use of this it may be desirable to turn Off Set::nosym.

Off[Set::nosym]

{a, _, b} = {1, 2, 3};

{a, b}
{1, 3}

Perhaps this is as close to a convention as we can find?

$\endgroup$
5
  • $\begingroup$ Provided that LongFunctionName[...] immediately evaluates to a list of matching length, which it probably should for an undelayed assignment. $\endgroup$
    – LLlAMnYP
    Commented Mar 9, 2017 at 13:15
  • $\begingroup$ @LLlAMnYP Yes, that is an unstated assumption, since e.g. {a, b} := foo[x] doesn't work anyway. $\endgroup$
    – Mr.Wizard
    Commented Mar 9, 2017 at 23:18
  • $\begingroup$ @Mr.Wizard I suppose LLIAMnYP meant {a,b} = {1,2,3} case. $\endgroup$
    – Kuba
    Commented Mar 10, 2017 at 7:51
  • $\begingroup$ @Kuba well, that would be a similar problem. $\endgroup$
    – LLlAMnYP
    Commented Mar 10, 2017 at 8:37
  • $\begingroup$ @LLlAMnYP Ok, I just wasn't sure if there is a misunderstanding or not :) $\endgroup$
    – Kuba
    Commented Mar 10, 2017 at 8:39
4
$\begingroup$

This one should not need to suppress messages:

Block[{a}, {a, b, a} = {1, 2, 3}];
a
b
(* a *) 
(* 2 *) 
$\endgroup$
1

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