jeudi 9 février 2023

Is there a recognized universal pattern to interrupt internal algorithm flow, by client's functor control?

Calling to generic software engineering collective knowledge,
is there a design pattern that would be best appropriate to interrupt the flow in an abstracted algorithm that runs a functor?

Example in pseudo code:

void ForEachIn(container, functor)
    for (x:container)
        functor(x);

// client:
optional<T> found;
ForEachIn({..}, [&](elem) { if (elem == jackpot) found = elem; });

Now you see, if we don't stop the for at first find, it's a "find last". If we do, it's a "find first".
(It could be another reason like useless cycle savings. Whatever you imagine)
Let's say this flow control is not a leak of abstraction, because the traversal scheme is advertised and well defined to the clients.

If I want to interrupt in the middle, the algorithm has to support flow interruption by being cooperative with the user's functor.
Maybe in that way:

void ForEachIn(container, functor)
    for (x:container)
        stop = functor(x);
        if (stop) break;

So the question is:
Do we know about a classic "universal" way for this?

Is it better through a reference parameter?
Is it better through a bool return?
an enum return ( enum Flow { Continue, Break }; )?
an enum ref parameter?
a strategy/policy?
a try catch throw?
a longjmp (joke.. or is it :p)?
something else?

This definitely sounds like a monadic problem that must be known since 1950.

Aucun commentaire:

Enregistrer un commentaire