chapel-lang / chapel

a Productive Parallel Programming Language
https://chapel-lang.org
Other
1.79k stars 420 forks source link

Should the 'set' type support a method to get the only element in the set? #21166

Open benharsh opened 1 year ago

benharsh commented 1 year ago

I was recently writing some code which used sets in order to leverage the "intersection" functionality, and where I wanted to find the one element in common between the sets. Right now I need to pretend to iterate over the intersected result and assert that there's only one element.

Should we have a method that returns the single element if one exists, or throws an error if there are either 0 or more-than-one elements?

var common = (first & second).one();

That said, perhaps this reflects a more core issue that could persist across various types that we should try to address at a higher level. Alternatively, we could try to support this kind of operation on iterable expressions. In initially writing this issue I was reminded that the only keyword is reserved in Chapel, so we could perhaps leverage that for some special iterable functionality:

var common = (first & second).these().only();
// becomes...
var common : <compiler infers the type>;
{
  // should optimize long-term, but for now is easily implemented with an array temp...
  var temp = (first & second);
  if temp.size != 1 then throw SomeError();
  common = temp.first;
}

Or add this to some kind of IterTools library:

var common = IterTools.first(A & B);
mppf commented 1 year ago

(in response to the Chapel 2.0 label) I would think this could be added as a non-breaking change?

bradcray commented 1 year ago

I've removed the label, interpreting @benharsh's thumbs-up as agreement.