1
$\begingroup$

The following doesn't work:

Lol[x_, y_] = Module[ {w=x+1, z = w + 1}, z]

because z refers to w. Is there a way to make it so that variable definitions within Module can refer to other variable definitions?

This is similar to let constructs in other languages.

$\endgroup$
  • 1
    $\begingroup$ Try this: Lol[x_, y_] := Module[{w, z}, w = x + 1; z = w + 1] $\endgroup$ – MelaGo May 23 at 22:21
  • 1
    $\begingroup$ Strongly related if not a dupe: How to avoid nested With $\endgroup$ – Leonid Shifrin May 23 at 23:27
4
$\begingroup$

I think you meant to use Lol[x_, y_]. At any rate, you can use With to do this, although the syntax coloring is bad:

Lol[x_, y_] := With[
    {w = x + 1},
    {z = w + 1},
    z
]

Then:

Lol[2, 3]

4

The syntax coloring should be fixed with the next version of Mathematica.

$\endgroup$
  • $\begingroup$ If With is the answer then it is a duplicate, if OP showed only a minimal example and Module is a key here, then it is not the answer. I know you know but readers may not know why Module was replaced with With without a word of explanation. $\endgroup$ – Kuba May 24 at 9:12
  • $\begingroup$ @Kuba The original post refers to the "let constructs" found elsewhere. That pretty much implies a With-like approach should be used, i.e. Module should not be a key requirement. $\endgroup$ – Daniel Lichtblau May 24 at 15:22
  • $\begingroup$ @DanielLichtblau thanks the comment. Seems like my initial comment is still valid though. $\endgroup$ – Kuba May 27 at 13:56

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.