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$
2
  • 1
    $\begingroup$ Try this: Lol[x_, y_] := Module[{w, z}, w = x + 1; z = w + 1] $\endgroup$
    – MelaGo
    Commented May 23, 2019 at 22:21
  • 1
    $\begingroup$ Strongly related if not a dupe: How to avoid nested With $\endgroup$ Commented May 23, 2019 at 23:27

1 Answer 1

5
$\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$
3
  • 1
    $\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
    Commented May 24, 2019 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$ Commented May 24, 2019 at 15:22
  • 1
    $\begingroup$ @DanielLichtblau thanks the comment. Seems like my initial comment is still valid though. $\endgroup$
    – Kuba
    Commented May 27, 2019 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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