2
$\begingroup$

Suppose I wish to create a MenuView where the evaluation of the rules is time consuming.

How would I delay evaluation of the right-hand-side of the arguments to MenuView until that item is requested?

Here is a toy example that illustrates my question (it calls expensiveFunction on a set of matched items).

iList = RandomInteger[{1, 20}, {100, 2}];

getPairs[pairs_List] := 
With[
      {cases = Echo@Cases[pairs, {a_, b_} /; (EvenQ[a] && EvenQ[b])]},
      MenuView[MapThread[#1 -> (expensiveFunction[Pause[.1];#2]) &, Transpose@cases]]
    ]

getPairs[iList]

The goal would be to Hold expensiveFunction[#2]& when the view is created, but release the hold when its label is requested. I've tried a few unsuccessful shots on goal with Hold and Attributes. Before going down the path of doing something with Dynamic, I was wondering if anyone with a better understanding of non-standard evaluation has a simpler solution.

$\endgroup$
2
$\begingroup$

You can delay evaluation with Dynamic:

#1 -> Dynamic[Pause[.1]; expensiveFunction[#2], SynchronousUpdating -> False] &

but you also need to set ImageSize->Automatic for MenuView, otherwise it will try to pre-render all Dynamics to determine appropriate ImageSize.

Full code:

getPairs[pairs_List] := With[
  {cases = Echo@Cases[pairs, {a_, b_} /; (EvenQ[a] && EvenQ[b])]},
  MenuView[
   MapThread[
    #1 -> 
      Dynamic[Pause[.1]; expensiveFunction[#2], 
       SynchronousUpdating -> False] &,
    Transpose@cases
    ],
   ImageSize -> Automatic
   ]
  ]
$\endgroup$
  • $\begingroup$ Wow. That was fast, @Kuba. Thanks. $\endgroup$ – Craig Carter Jun 7 '18 at 12:12
  • $\begingroup$ I am looking at this again--I am not sure why that works. What is causing the Dynamic to update when the label is accessed. Good learning moment. $\endgroup$ – Craig Carter Jun 7 '18 at 12:18
  • $\begingroup$ @CraigCarter Dynamic content is sent to evaluation when Dynamic is 'visible''. Only one at a time can be visible here so this is what holds it. $\endgroup$ – Kuba Jun 7 '18 at 12:24
  • $\begingroup$ Ahh. Yes, good learning moment. Thanks again @Kuba $\endgroup$ – Craig Carter Jun 7 '18 at 12:34

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.