Concept of Iterators and Containers

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:

function Sum(entry)
    local
total=0

    if
(type(entry)==”tableor type(entry)==”Vector”) then
        for
i=1,#entry do
            total=total+entry[i]
        end

    elseif
(type(entry)==”Matrix”) then
        for i=1,#entry do
            total=total+entry[{i}]
        end

    elseif
   
-- querying data types goes on
    end

return
total
end

 

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:

function Sum(container)
    local
total=0

    for key, value in pairs(container) do
        if
(type(value)==”number”) then
            total=total+value
        end
    end

    return
total

end

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.