1
$\begingroup$

I was playing with GeneralUtilities`PrintDefinitions in V10.1, and find some of native Mathematica functions using Macros`HoldSequence and Macros`ReleaseHoldSequence in some sort of error handling.

Someone knows why this is used? How it works?

Here is the DeleteDuplicatesBy code structure.

Self:DeleteDuplicatesBy[expr_,f_]:=Module[{r$},

  r$=Which[
    	!Quiet[TrueQ[!AtomQ[expr]||AssociationQ[expr]||Head[expr]===SparseArray]]
    	,Message[DeleteDuplicatesBy::normal,1,HoldForm[Self]];$FailRHS
    ,True
    ,HoldSequence[
        Which[
        ListQ[expr]
            ,Values[GroupBy[expr,f,First]]
        ,AssociationQ[expr]
            , Association[Values[GroupBy[Normal[expr],f@*Last,First]]]
        ,Head[expr]===SparseArray
            ,DeleteDuplicates[expr,f[#1]===f[#2]&]
        ,True
            ,expr[[Values[GroupBy[Table[{f[expr[[i]]],i},{i,Length[expr]}],First,First]][[All,2]]]]
        ]
      ]
    ];

  ReleaseHoldSequence[r$]/;!MatchQ[r$,$FailRHS|HoldSequence[$FailRHS]]

]
$\endgroup$
  • 1
    $\begingroup$ Well, this is just a way to process errors. Since Which is evaluated right away, the fact that it reached tha part wrapped in HoldSequence means that there are no errors in the input. The $FailRHS symbol is used to separate the error - reporting logic (issue messages etc) at the top from the actual decision for the rule to match or not match, at the bottom. There are many ways to do this, this is just one of them. $\endgroup$ – Leonid Shifrin May 8 '15 at 16:18

Your Answer

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

Browse other questions tagged or ask your own question.