Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've never thought about adding upvalues to CompoundExpression -- what kinds of applications have you used this for?


In fact, here's a silly idea, executed with two kernels:

  SetAttributes[Parallel, HoldAll];
  CompoundExpression[x__Parallel] ^:= ParallelCombine[Identity @@@ # &, {x}]

  In[28]:= (Parallel[Pause[3]; 3]; Parallel[Pause[3]; 4]; Parallel[Pause[3]; 5]) // AbsoluteTiming
  Out[28]= {6.00864, {3, 4, 5}}


I'd never seen UpSetDelayed used before (I've always used the longer /: notation), that's interesting.

A silly idea I was thinking about is supporting

  With[{x = 2}];
  With[{y = 3}];
  x + y
for

  With[{x = 2},
    With[{y = 3},
      x + y]]
to reduce nesting.


Note that you can nest within a single With:

  With[
    {x = 2},
    {y = 3},
    x + y
  ]
Though this form is not (yet) documented.

Crucially, y could refer to x here.

It can really help with the indentation.


I use notebooks primarily -- it would be nice if syntax highlighting didn't put x+y in scary red :-)

Something I've wondered: would it be possible to support With[x = 2, x + x] when there's just a single variable? It's certainly very low-priority, but it saves a few keystrokes when doing quick calculations.


Yep, the proper syntax highlighting will follow when documented.

There was actually a massive internal discussion in 2015 re: With[x = 2, x + x]. And With[x = 2, x + x] actually did work for a time.

Unfortunately, several other ideas like With[x, x+x] and Module[x, x+x] (which was unintuitively NOT implemented as Module[{x}, x+x]) also got thrown into the conversation and things became confused, these uses were seen to be problematic, and soon the baby was thrown out with the bath water.

So technically yes, With[x = 2, x + x] could work, but it is unlikely that it will ever be implemented in product.


I'm sure there are subtle bugs, but it seems to work in a simple case:

  SetAttributes[Have, HoldAll];
  Have /: HoldPattern[CompoundExpression[x___, Have[s_Set], y__]] :=
    CompoundExpression[x, With[{s}, CompoundExpression[y]]];


  In[698]:= (Have[x = 2];
             Print[x];
             Have[y = 3];
             Print[y];
             x + y)

  During evaluation of In[698]:= 2

  During evaluation of In[698]:= 3

  Out[698]= 5


Literally none, ever. But you have the option!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: