Programmer Bedtime Stories: A Dame, Two Spells, and a Scope

Ahn put down the scroll, then summoned a magical display. Schmendrick had used the increasingly popular magical language from the South Seas, known as JavaScript, and a snippet of invocation appeared on the display. “I have simplified Schmendrick’s invocation to make the error easier to see.”

“This is the function in his invocation to make Blueberry tarts. When called it asks for the number of tarts to be made on line 2 and uses a container named num to hold that number and be easy to use. Then it asks for the minimum number of blueberries on line 3, assigning that to a container as well.”

“On line 4, it begins the process, starting a loop to perform the tart making process, using a container named ‘I’ to track the number of times it’s run. But notice that ‘I’ is used again on line 6. Many Wizards use ‘I’ for loops out of habit, but rather than use different container names, he uses the ‘var’ word of power to command the two ‘I’s to each be unique containers. One problem though…”

“var only makes a container unique per function. Those loops are also known as blocks. And to make a container unique to a block, you use ‘let’ instead of ‘var’. So with ‘var’ and ‘var’, instead of var and let, the second command for uniqueness is ignored and the same container is used by both loop operations.”

The loop adds 1 to I, then checks if it is greater than or equal to the number in min. If it is, the loop is executed. So, when the addition of berries was done, I would be the number of berries plus one. It would be increased by one again with the completion of the tart. If the number of berries was 1 smaller than the number of tarts, equal to the number of tarts, or greater than the number of tarts, I would then be greater than num and the spell would believe it had made all the tarts after the first one. That’s why we kept getting only one tart.”

“But, if the number of berries was two or more less than the number of tarts, each time the berries were counted, it would reset the number of tarts to less than the number requested. And thus…”

Schmendrick slapped his forehead. “Endless flow of tarts! Because he kept getting just one tart, he probably kept raising the amount he asked for. Once he asked for a dozen ten-berry tarts…”

Ahn raised her hand to stop him. “I do believe it was related to these containers, but it was actually you who set the number of berries too far below the number of tarts he requested.” Ahn handed him the mirror with his timer incantation.

Pages ( 13 of 17 ): « Back1 ... 12 13 14 ... 17Next »

Leave a Reply

Your email address will not be published. Required fields are marked *