Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
3  
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. –  rcollyer Jun 18 '13 at 1:06
    
@rcollyer thanks for the shout-out! :-) –  Mr.Wizard Jun 18 '13 at 15:30
    
@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. –  rcollyer Jun 18 '13 at 15:32
1  
@rcollyer Probably you know it, but I'd like to mention that languages with this property are called homoiconic. –  Vladimir Reshetnikov Jun 18 '13 at 20:34
    
@VladimirReshetnikov yes, having recently learned that word ... and it has some very interesting consequences. –  rcollyer Jun 18 '13 at 20:37

1 Answer 1

up vote 7 down vote accepted

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.

share|improve this answer
1  
StackOverflow reference: stackoverflow.com/a/5149656/618728 –  Mr.Wizard Jun 18 '13 at 15:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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