Unpaid shortcut redux
August 10, 2019 at 7:54 AM by Dr. Drang
There’s an old programming adage that says you can write Fortran in any language. Although I’ve made progress, I’m still writing parts of my Shortcuts in Fortran.
After reading my last post, Majd Koshakji tweeted me a couple of suggestions:
By following this advice, I was able to make the Unpaid shortcut both shorter and easier to understand. Here’s the before and after:
The first thing to notice is that the
action near the bottom of the shortcut—the one with the regular expression that uses a lookahead—has been replaced with the far simpler action.There are two things to say about this:
I didn’t know there was a
action. Discovering what’s available in Shortcuts is still a struggle for me.Even if I’d known about it, I’m not sure I would have guessed that
adds thousands separators. There’s no checkbox for it in the action itself (as you see in Numbers, for example), nor is there any mention of it in the highly detailed popup documentation.
But using
simply replaces one action with another. The real shortening comes from using Majd’s other suggestion.The
action performs any one of several calculations on a list of numbers.I knew about total
variable, I didn’t see any advantage.
As is so often the case with Shortcuts, I underestimated the power of magic variables. The
loop creates a list on its own; with each pass through the loop, it adds the output of the last action within the body of the loop to that list. That magic variable, called Repeat Results, is the output of the loop.So there’s no need to build a list of numbers explicitly, Shortcuts is doing it for me. All I need to do use is pass it into the
action.It’s shown up above, but let’s show the new version of Unpaid its own:1
There are lots of ways to get a program to work. But every language has certain characteristic features that give it syntactical advantages. You need to learn those features if you want to program in a style that’s efficient for that language. Perl has a magic variable, $_
, that is—or can be—the implicit argument to lots of functions; idiomatic Perl uses that magic variable to streamline its code. Idiomatic Python uses list comprehensions to eliminate certain types of loops.
I’ve been getting better at using magic variables in shortcuts. I don’t put the output of scalar operations (like the
action) into explicit variables anymore. But I didn’t understand how loops output lists until now.Thanks to Majd for the suggestions on this specific shortcut and for helping me become a better Shortcuts programmer in general.