News for hackers. Stuff that matters.
Re:The use of `class` for things that should be simple free ... by wwright on Friday May 29, 2020 @08:00AM (#23348925)
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.)

There are no comments on this comment yet.