optional icon indicating copy to clipboard operation
optional copied to clipboard

Interaction with containers

Open loskutov opened this issue 4 years ago • 1 comments

Let's consider the following example:

struct ipv4;
optional<ipv4> parse_ipv4(string_view);
// Useful for parsing some config for example
optional<vector<ipv4>> parse_many_ips(vector<string_view> const&) {
  // how do I implement this?
}

With std::optional such function could be implemented as follows:

std::optional<vector<ipv4>> parse_many_ips(vector<string_view> const& strs) {
  vector<ipv4> result;
  for (auto s : strs) {
    if (auto ip = parse_ipv4(s)) {
      result.emplace_back(*ip);
    } else {
      return std::nullopt;
    }
  }
  return result;
}

And with tl::optional... The same? The additional functions don't seem to provide any help. On the other hand, in a functional language this would be a one-liner: parseManyIps = traverse parseIpv4.

Providing full standard library support for Foldable/Traversable concepts does obviously seem out of scope for this library, however ad-hoc support for some common cases such as the example above would be quite useful.

loskutov avatar Nov 07 '20 14:11 loskutov

Just my 2c on this:

  1. parse_many_ips(...) has a strange return type. I would rather return vector<ipv4> directly. If it is empty then this is equivalent of not presence. This way one "layer of optional" is removed.
  2. With the first point in mind, what we would need in C++ are the plain type classes of functional languages. We would need the functor instances for std::vector (like "map") or any other container for that matter.
  3. Your implementation should directy work with tl::optional as far I can tell.
  4. I agree that a fold on monads would be nice to have, but again this would require a Foldable typeclass.
  5. For what its worth, I would also like to see an Applicatve interface :)

Other than that, I think the author has given up on this library. It is still very useful to me, but as the author already stated in another thread, tl::optional is not really a sum type, so we simpy cannot have all the benefits of functional languages(just yet).

juxeii avatar Nov 13 '20 10:11 juxeii