The concept of iterators and containers are not new and as a matter of fact, the STL library of C++ language has been designed based on this simple but very powerful concept. As already mentioned most of the built-in data structures in ScienceSuit are iteratable containers and Lua tables are, by default, iteratable.
When designing a new function, understanding the concept of iterators and containers can save you significant amount of time and furthermore make your code significantly more readable. Let’s demonstrate the concept with a simple example. Suppose we want to design a simple function that finds the sum of the values and we want this to work, if not all, on many data structures:
It is immediately realized that as the number of data structures increases, there will be more if blocks and it is indeed very easy to forget and rather cumbersome to add a data structure as the number of functions and data structures increases. Therefore, we will end up with an error-prone, hard-to-read and time-taking code. Here, comes the life-saver: Iteratable containers
Had we used the concept of iteratable containers, we could have designed the function in the following way:
One can quickly notice that the code is more concise, readable and less error-prone. Furthermore, there are no if blocks checking the type of the container. As long as the function argument, namely container, is an iteratable one, the code will work regardless of its type.