1

In Chapel, I can count the number of array elements equal to a given value as

var a = [1,2,5,5,5];
writeln( a.count( 5 ) );  // this gives 3

but a similar method does not seem to work for counting the number of true elements:

writeln( count( a > 1 ) );
writeln( ( a > 1 ).count( true ) );

In this case, do I need to write an explicit for-loop, or is there any other function (or method) for this purpose...?


Update

After some more experiment, it seems that if I save the result of a == 5 to a new array

var mask = ( a == 5 );

then it works as expected

writeln( mask.count( true ) );  // gives 3

So, a == 5 may be representing something different from an array object and so does not provide .count() directly?

user3666197
  • 1
  • 6
  • 50
  • 92
  • do you consider: `a.count( 5 )` equivalent to: `count( a > 1 )` ??? – Nir Alfasi May 11 '17 at 22:44
  • Oh no, sorry, I tried to do a more "generalized" counting using comparison operators. To match the first example, I want to try count( a == 5 ). –  May 11 '17 at 22:47
  • Chapel supports promotion, so the expression `a == 5` essentially promotes the `==` operator, resulting in a multiplicity of values, `false false true true true`. – Brad May 12 '17 at 00:13

1 Answers1

2

The problem you're having is that the .count() method is defined on arrays, so calling it on a is fine. However, the expression a > 1 isn't an array, it's an iterator expression, and iterator expressions don't (currently) support the .count() method nor do they coerce to arrays( see* ).
So the problem doesn't have anything to do with counting booleans.
You'd have a similar problem if you counted other promoted expressions on arrays:

var a = [ 1, 2, 5, 5,  5],
    b = [ 2, 4, 6, 8, 10];

writeln( ( a + b ).count( 6 ) );

Two unsatisfying ways to address this would be

(1) to cast the iterator expression into an array or
(2) to store the iterator expression into an array variable.
But the more typical way to write this expression in Chapel would be to use a reduction:

writeln( + reduce ( a > 1 ) );

*) = perhaps one of these things should change...

user3666197
  • 1
  • 6
  • 50
  • 92
Brad
  • 3,839
  • 7
  • 25
  • I had not read your answer but just kept on experimenting (so updated my question before reading your answer, sorry!). But okay, now I understand... I will also experiment with the reduction approach. thanks! –  May 12 '17 at 00:35