I am currently trying to teach myself scala by rewriting projects from my intro CS class, which was taught in C++. In addition to just learning the syntax I am trying to gain understanding of how functional programming works and what is considered good functional programming style.
Below I've included both the original code, which is a simple while loop that continues looping until the user selects the 'quit' option, and my attempt at a functional equivalent. Have I done this correctly? What could be improved?
Original imperative version in C++:
int main()
{
int option = -1;
while (option != 3)
{
cout << fixed;
cout << "Please select one of the following:" << "\n1 - one" <<
"\n2 - two" << "\n3 - quit" << endl;
cin >> option;
if (option == 1)
{
cout << "selected 1" << endl;
}
else if (option == 2)
{
cout << "selected 2" << endl;
}
else if (option == 3)
{
cout << "selected quit.\n";
}
else
{
cout << "Sorry, that command is not recognized. ";
}
}
return 0;
}
My attempt at a functional version in scala:
def menu(option: Int) {
println("""|Please select one of the following:
| 1 - one
| 2 - two
| 3 - quit""".stripMargin)
if (option == 1) {
println("selected 1")
val opt = StdIn.readInt
menu(opt)
}
else if (option == 2) {
println("selected 2")
val opt = StdIn.readInt
menu(opt)
}
else if (option == 3) {
println("selected quit")
}
else {
println("Sorry, that command is not recognized")
}
}
def main(args: Array[String]) {
println("""|Please select one of the following:
| 1 - one
| 2 - two
| 3 - quit""".stripMargin)
val opt = StdIn.readInt
menu(opt)
}