started learning racket today. I was attempting to find the correct way to append via a loop but could not find the answer or figure out the syntax myself.
For example, if I want a row of nine circles using hc-append, how can I do this without manually typing out nine nested hc-append procedures?
The first thing you need to realize is that “looping” in Racket is really just recursion. In this case, you want to chain a bunch of drawing calls together. If we wrote this out, our target goal would be this:
I am assuming all of our circles are going to be the same radius.
Now, since we’re going to be writing a recursive method, we need to think of our base case. We want exactly nine circles drawn. Let’s call this maximum number of circles
max. Our base case, when we break out of our “loop” will be when we reachmaxiterations, or when(= iterations max).Now for the recursion itself. We already know we need to pass in at least two variables, the current iteration
iterations, and the maximum iterationmax. If you look at the code above, you’ll notice that the repeating element in all of the “loops” is the(circle 10). Now there are a number of ways you could pass that along — some people would choose to just pass the radius for example — but I think the easiest way would be to pass in the pict of the circle.Finally, we also have to pass along the picture we’ve done so far. That is, as we append a circle to our chain, we need to pass this back into the recursive method so we can keep appending.
Now that we’ve got that squared away, we can define the structure of our recursive method, which we shall call
circle-chain-recursive:The “guts” of our method will be an
if. If we’ve reached the max iteration, return the output. Otherwise append another circle, incrementiteration, and call the method again.I personally don’t like calling recursive looping methods like this directly, so I would write a helper method like this:
Now if I want a series of 9 circles with radius 10, all I have to do is call
(circle-chain 9 10).You’ll notice that I passed
(circle 0)as in as the parameter calledoutput. This is because thehc-appendmethod requires apictparameter. Since we’re not starting out with any circles, I passed it the equivalent of a “blank” or nil pict. There may be some other way of passing a “blank” pict, but I’m not too familiar with theslideshow/pictlibraries to know it.I hope that clears it up a bit.