3 ms·
IMO it’s even simpler to use a monad-type extension to functions to suspend state. (This can be coroutines/generators, explicit Haskell monads, some macros enca
by wwright 6y ago
IMO it’s even simpler to use a monad-type extension to functions to suspend state. (This can be coroutines/generators, explicit Haskell monads, some macros encapsulating longjmp or whatever.)
queue <- { root }
while queue is not empty
node <- dequeue one node
# One of the following:
# for a simple function approach…
if predicate(node)
return node
# or for a monadic approach, can be overloaded generically…
yield! node
for child of node
enqueue child
The monad-style extensions fits with the other pieces of the language much more naturally IMO. You could easily use a predicate monad to regain the functionality of the naive implementation, or a more complex monad if you want a complex BFS traversal, but the function looks almost identical either way.
Python and Ruby and Lua and JavaScript even do this! C++20 will probably make this somewhat more common too.
(The word “monad” may set off sirens here, but it really just refers to a feature similar to but somewhat more generic than “yield” in a coroutine/generator.)