CALL NOW 713-568-9753
30 Jul 2015
Learning Scala By Example, Chapter 2
Mark KerznerPosted in: Dev Stuff 0

In the previous, first installment, I explained why it is worth your while to learn Scala. Now I want to introduce you to chapter 2 of “Scala by Example.”

Remember, I am not writing a new book, but elucidating the one by Martin Oderski. This chapter teaches functional programming. In brief, functional programming means, “If you want the computer to do something, say so, but don’t micromanage, telling it exactly how to go about it.”

For example, in sorting, you can spell out every variable to use for sorting an array, or you can say the following

1. If the array is of length 1, it is already sorted.
2. If it is longer than that, break it into three parts: the center, the left and the right. The center is of length 1, and you know how to sort it. The left and the right – sort them by applying the same sort function, but now to smaller arrays.

This is a recursive call, and it exists just as well in regular, non-functional programming. What makes the code functional is that we express the algorithm in terms of operations, not step-by-step instructions.

This may remind you of the following joke. How does a physicist boil tea? He pours the water in the kettle and puts it on the stove. If there is already water in the kettle, he just puts it on the stove. How does a mathematician boil tea? He, too, pours the water into the kettle and puts it on the stove. If there is already water in the kettle, the mathematician pours it out, and now he has a problem that he already knows how to solve.

How to use chapter 2? Read it leisurely at first, even if you don’t understand all. Then run the code in the project on GitHub. Then read the chapter again, now it will make more sense. Repeat.

But you may ask, how do I run the code? First, fork the project on GitHub here.

fork

Now clone it on your computer.

My clone command:

git@github.com:elephantscale/learning-scala.git

 

Yours will point to your copy of the repository.

Now open it in IntelliJ. If you use another IDE, you don’t have to ask me how to do you, you will already know. Now set up the first test by setting the run configuration as shown in the picture here. Run the test. You are done.

run-config

(Incidentally, I m using the “Darkula” theme, it looks “hacky” and it saves  battery life on a laptop. To get to a Theme, press Ctrol-Shft-A, then search for ‘Theme’).

Where to go from here? Write your code for another recursive algorithm. Greatest common denominator is one of the easiest that comes to mind. Add your code for it to the package ‘chapter02’ and add the test for it to the package chapter02 in the testing directory. Since you have forked the project, you can commit your solution and push it to your repository. Now showcase it and tell the world about it. Be a Giant For a Day!

Leave a Reply

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