4 ms·
Programming in Mathematica is weird. I've done a whole course in machine learning using only mathematica (as opposed to more obvious choices, like matlab or pyt
by lindbergh 11y ago
Programming in Mathematica is weird. I've done a whole course in machine learning using only mathematica (as opposed to more obvious choices, like matlab or python) and while writing small functions was very easy (and functional programming fun), compounding those functions without using global variables was very hard. I kept using the Module construct where each local variable has to be declared, and it ended up being a mess. I always have a running session of Mathematica running for quick calculation or plotting (easier imo than matlab+nupy / matlab), but I would never consider it for larger projects. But I've never seen a larger codebase so maybe there's some kind of design pattern essential for this language.
- taliesinb 11y agoModule (and its dynamical scoping cousin Block) can be clunky to use because you have to declare the local variables you wish to use up-front. Other than that it's not 'weird'. I write a lot of Mathematica code for my job. To make life easier I've built in a macro system that makes day-to-day programming a whole lot more pleasant. It will be available in Mathematica 10.4 in the GeneralUtilities package that ships with Mathematica. One of the built-in macros is a construct that automatically localizes any variables that occur as the L-value of an assignment: Needs["GeneralUtilities`"] foo[x_, y_] := Scope[ z = x * y; PrimeQ[z + 1] ] This gets rewritten at definition time to be: foo[x_, y_] := Block[{z}, z = x * y; PrimeQ[z + 1] ] It's a small thing, but it adds up, especially for large functions, and indeed its silly this isn't a core feature of the language. There are a couple other nice features of Scope, too, like the ability to use a single quote ' anywhere in the body of your function to Echo the value there to the current notebook without actually changing the behavior of the code -- essentially a very lightweight form of 'debugging print'. That also makes a huge difference. And it has some more powerful variants, like "z '= 2 * 3" will echo a line that explicitly says "z = 6", rather than just "6". Likewise '' means EchoHold, which prints the expression before being evaluated AND afterwards, so you'll see "z = 2 * 3 = 6" in the above case. Lastly ''' means Tap, which is a higher-order form of EchoHold which instruments a function to echo its input and output (again without changing behavior). So Fold[Plus''', Range[10]] prints out all the intermediate steps in the fold. There's a variety of features that add a very lightweight syntax for monadic and exception-based error handling, but that's not quite stable enough to advertise yet. Same goes for debugging: there's some really powerful stack browsing, history capture and replay features, but again not quite stable enough to advertise for this version.