Pages

Saturday, December 30, 2017

Singing with Loops

Loops are programming constructs for repeating a set of instructions until a given termination a criterion is met.

Ann cheered at the sight of the brightly lit inn. A sign by the door read, “One night only! The world famous bard Larry de Loop!” After another full day of walking, she felt tired and seemed no closer to finishing her quest. But, at least, she’d found a place to rest. And some cheerful music might help take her mind off her quest.

Ann chose a small table by the stage. After ordering a bowl of Surprise Stew, regrettably the only item on the menu, she settled in for the show.

Though unable to play even a basic tune on his accordion, Larry de Loop was the most enthusiastic bard Ann had seen. He belted out three simple songs, then asked for requests.

“The Ballad of Lady Algorithm,” called Ann, wanting to hear the tale of her favorite adventurer.

Larry looked surprised. “I’m sorry miss. I only sing songs in loop form.”

“Loop form?” Ann asked. “I’ve never heard of that style of music.”

“It’s quite popular in the North. The songs have to use either FOR loops or WHILE loops. Loops are constructs for repeating things until some conditions are met.”

“What?” asked Ann. Naturally she was familiar with the concept of loops. They were a basic building block of algorithms. She used loops in archery (while you have arrows, shoot at the target), cooking (stir for two minutes), counting coins (for each coin, add its value to the total), and even walking (while I’m not there yet, take another step). But she’d never heard of loop-based music.

“I mostly sing in FOR loops,” explained Larry. “A FOR loop iterates over a set number of things. 99 Bottles of Beer on the Wall uses a FOR loop. FOR each number of bottles from 99 down to 1, sing a verse. Or perhaps you’ve heard of old McDonald’s Farm? FOR each animal on the farm, sing about the cute noises it makes. Or—“

“Aren’t those songs all quite repetitive?” Ann interrupted. Of course, repetition was precisely the function of a loop.

Larry smiled broadly. “That’s why I also use a WHILE loop. WHILE loops repeat a set of actions until a condition is met. In my case I always use the same loop: WHILE no one has thrown a tomato at me, keep singing. So once the first tomato is thrown, I know it's time to stop.”

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.