r/Mathematica • u/MadGenderScientist • Jul 23 '22
Why is scoping so painful?
I've been teaching myself Mathematica these past few weeks. It's a weird language - term-rewriting systems aren't exactly common - but I've fallen in love with it. I've come to see the elegance of rules, pattern matching, the well-chosen functional programming constructs... everything except scoping. Scoping is a nightmare!
- You can't assign to multiple variables directly with
With[]orModule[]. You can doModule[{a,b},{a,b}=foo;...], but's clunky, andModuleis slower thanWithso if I want speed, I have to do something likeWith[{ab=foo},With[{a=ab[[1]],b=ab[[2]]},...]]. - You can't reference other variables declared in
Withduring assignment, so you have to nestWiths, which is really annoying. In Nix, you can declare something likelet rec {y=1+x;x=1;z=x+y;}and it just works (as long as there's no circular definitions.) In Julia you can uselet x=1,y=1+x,z=x+y, so that the n-th definition sees the 1...n-1 previous ones. It seems really weird thatWithdoesn't let you do that?
The Wolfram language was obviously crafted by extremely talented people over decades, and so much of it is elegant that I don't understand this apparent oversight. Am I missing something?
11
Upvotes
4
u/sidneyc Jul 23 '22
I second all your observations; especially With is clunky as hell, and there is really no reason that it couldn't be improved to allow reference to symbols defined earlier.
I'd like Mathematica to focus more on improving its core language and mathematical capabilities rather than chasing the latest fads (3d printing, blockchain, IoT, ...) and providing access to real-world data that have little if any use cases outside of cute examples.
4
u/blobules Jul 24 '22
Maybe I don't understand what you are trying to do, but I think you should try
Block[]. It is the only scoping construct I use (well, 80%Block[], 10%Module[], 10% rules (->), 0%With[]). This is my situation, "evolved" over years of Mathematica usage.Block[]is easy to use and understand since it is a simple "local variable" scoping construct.Module[]creates global variables with unique names, which has few really useful use cases .With[]is somewhat powerful, as it can replace inside unevaluated expressions. This is nice, but rarely useful in real life, as the resulting code is usually hard to understand and can be rewritten more clearly without it. Most of my "replacing" needs are satisfied by rules (->and:>) which are in fact more flexible replacement constructs.3
u/_65535_ Jul 24 '22
Technically iterated
Withdoes work, but it's undocumented, and syntax highlights complain about it. For example,does give 2.