10
$\begingroup$

Consider the following expression:

Block[{Print = CopyToClipboard}, doSomething[]]

Now all calls to Print from doSomething[] (and all other functions it may invoke) will copy values to clipboard rather than printing them. Suppose I want to modify this expression such that all calls to Print both copy values to clipboard and print them.

Block[{Print = (CopyToClipboard[#]; Print[#]) &}, doSomething[]]

I need something similar to the above, but which doesn't go into an infinite recursion and where the occurrence of Print within the pure function retains its global meaning that it had before the execution entered the Block. Is it possible?

I understand the difference between Block and Module, and I need to use Block to create a dynamic (rather than lexical) scoping.

$\endgroup$
5
  • 3
    $\begingroup$ Since you are augmenting a behavior, you are looking for the Villegas-Gayley trick. There are many examples on this site, my personal favorite is from Mr.Wizard. $\endgroup$
    – rcollyer
    Jun 18, 2013 at 1:06
  • $\begingroup$ @rcollyer thanks for the shout-out! :-) $\endgroup$
    – Mr.Wizard
    Jun 18, 2013 at 15:30
  • $\begingroup$ @Mr.Wizard you're welcome. I'm tempted, if I find the time, to add to the design patterns question the most fundamental pattern in mma: there is no distinction between code and data, and that is a perfect example of it. $\endgroup$
    – rcollyer
    Jun 18, 2013 at 15:32
  • 2
    $\begingroup$ @rcollyer Probably you know it, but I'd like to mention that languages with this property are called homoiconic. $\endgroup$ Jun 18, 2013 at 20:34
  • $\begingroup$ @VladimirReshetnikov yes, having recently learned that word ... and it has some very interesting consequences. $\endgroup$
    – rcollyer
    Jun 18, 2013 at 20:37

1 Answer 1

9
$\begingroup$

What you are looking for is the Villegas - Gayley technique:

Internal`InheritedBlock[{Print},
    Unprotect[Print];
    Module[{inPrint},
       Print[arg_]/;!TrueQ[inPrint]:=
          Block[{inPrint = True},
              (CopyToClipboard[#]; Print[#])&[arg]
          ];
    ];
    your-code
]

Here, the Internal`InheritedBlock is used to make sure that the redefinition of Block remains local to your execution stack - it is also a dynamic scoping construct, but it preserves the old definitions, unlike Block.

$\endgroup$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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