MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: A version of With that binds variables sequentially

  • To: mathgroup at smc.vnet.net
  • Subject: [mg94641] Re: A version of With that binds variables sequentially
  • From: rych <rychphd at gmail.com>
  • Date: Thu, 18 Dec 2008 07:23:20 -0500 (EST)
  • References: <gi5jof$prg$1@smc.vnet.net>

On Dec 15, 12:49 pm, "D. Grady" <D.C.Gr... at gmail.com> wrote:
> Many times when I'm programming, I write code like this:
>
> With[{a1 = 5},
>  With[{a2 = f[a1]},
>   With[{a3 = g[a1, a2]},
>    h[a1, a2, a3]]]]
>
> I wish I could write this instead:
>
> With[{
>   a1 = 5,
>   a2 = f[a1],
>   a3 = g[a1, a2]},
>  h[a1, a2, a3]]
>
> Although With doesn't work this way, I didn't see any reason that it
> shouldn't, so I wrote a function called WithMany.  It works by taking
> something in the second form above and holding all of the arguments,
> expanding out to the first form, and then releasing the hold.
>

I've done something similar in the past. Here is my version:
Off[With::"lvlist"]
Off[Module::"lvlist"]
ClearAll[WithWith, WithModule]
SetAttributes[{WithWith, WithModule}, HoldAll]
WithWith[x__, expr_] :=
 ReleaseHold@
  Fold[With[#2, #1] &, Hold[expr],
   Reverse@Map[Hold, Unevaluated@{x}] /.
    Hold[h_[y__]] :> Hold[{h[y]}] /; h =!= List]
WithModule[x__, expr_] :=
 WithWith[xh =
   Reverse@Map[Hold, Unevaluated@{x}] /.
    Hold[h_[y__]] :> Hold[{h[y]}] /; h =!= List,
  xh1 = First@xh,
  ReleaseHold@Fold[With[#2, #1] &, Module[xh1, Hold[expr]], Rest@xh]
  ]

I think if I spend some time deciphering it, it's going to look the
same. (I must never never never write undocumented "one-liners")
Igor



  • Prev by Date: Re: Forcing Trig Identities
  • Next by Date: SaveDefinitions in Manipulate is not saving definitions from packages
  • Previous by thread: Re: A version of With that binds variables sequentially
  • Next by thread: Evaluate ?