mardi 28 février 2017

Ways to enumerate a sequence of input data

There are a couple of ways to traverse and process a range of data, but when things get more complex, it becomes quite hard, too.

If each operation is independent, life is easy:

[1] modification

for(auto&& x : v)
    x += 1;

[2] access

for(const auto& x : v)
    sum += x;

If things get more complicated, ways to handle an element are dependent to the context (parsing for example). Then we have to maintain an automaton:

[1] explicit state

// I think this method is quite unintuitive though
auto state = kDefaultState;
for(const auto& x : v)
{
    if(state == kFirstState)
    {
        // deal with x...
        // transfer state
    }
    else if(state == kSecondState)
    {
        // deal with x...
        // transfer state
    }
    else
    {
        // ...
    }
}

[2] implicit state hidden in the code flow(create a reader class)

// this method require a lot more extra coding and redundant bound check
auto reader = CreateReader(...);
while(reader.Exhausted())
{
    if(reader.Try(...))
    {
        // ...
    }
}

while(reader.Exhausted())
{
    // ...
}

I'm wondering if there are some other better styles to deal with such kind of problems.

Aucun commentaire:

Enregistrer un commentaire