Scala Foundation Course - Custom Loops in Scala


Welcome back. The next item in the Scala control abstraction is the most interesting control abstraction topic. I said Scala gives you an ability to create new control abstractions of your own. If this is true, can we implement a repeat until loop in Scala? Let's try it.

Repeat Until Loop in Scala

Do you remember function currying? We will use function currying to develop this example.
You might have already used a Repeat-Until loop in other programming languages. Let's take a simple example to refresh the usage semantics of a Repeat-Until loop. The repeat-until loop works something like this.

Repeat the body until the condition becomes true. Here is the first version of the code.

The code is simple. It takes two arguments. We take them in two different groups to enable function currying. We will pass the body of the repeat into the first parameter. Then we will pass the condition into the second parameter. So, the below function is using a repeat loop.


We have achieved almost everything that we desired. Just a small glitch is left. In the current version, we don't use the until keyword. That looks little awkward. We can fix that as well. Here is the next version.

This code is almost same as the curried function. We already learned in the earlier videos that when we pass the parameters of the first group of a curried function, Scala applies them to the code and returns a brand-new function with remaining parameters. The curried syntax does it automatically. I changed the code to do it manually. That's the only difference in the second version. Otherwise, both the versions are essentially same. You might be wondering if both the versions of the code is same, why I did that?
The function currying does the same thing automatically, but then we don't have control over the name of the returned function.
But to be able to use the until keyword, we wanted to give a name to the next function. And that's why we take the control in our hand and create a new version of the code. This new version is the manual implementation of function currying. But we are not done yet. If you try accessing the until method, you will get an error.
To achieve this, you need to place the new keyword in front of the function body and create a third version of the same code.

That does the trick because you get a reference type object with a method named as until. That allows you to create repeat until loop in Scala.
Great! So you learned that Scala allows you to create new control abstraction of your own. But control abstraction doesn't mean creating new looping constructs like repeat-until. The control abstraction has a wider sense. And that's the topic for the next video.
In the next video, I will take the notion of defining our own control abstractions and talk about Higher Order Control Abstractions in Scala.


You will also like: