In reply to ABD_91:
It might help to explain how the sum() reduction method calculates its result.
array.sum() without awith {} clause expands to
typedef int element_type;
element_type array[];
element_type item;
element_type sum = 0;
foreach (array[index] ) begin
item= array[index];
sum = sum + item;
end
It’s important to note that the datatype of
item and
sum is the same datatype as each element of the array. That means if the array element type is a single bit, the
item and
sum type is also a single bit. Instead of getting an intended count of 1’s, you get the odd parity of 1’s
The with {} clause substitutes what gets added to the sum. It also changes the sum data type to match the type the with {} clause. So if you had
bit array [];
array.sum with (int'(item));
that gets expanded to
typedef bit element_type;
element_type array[];
element_type item;
int sum = 0;
foreach (array[index] ) begin
item= array[index];
sum = sum + int'(item);
end
which gives you the count of 1’s as an int.
When you tried
a.sum() with (item == 1)
that has the problem that the resulting datatype of an equality expression is 1 bit. You run intto the same problem of not counting the number of times the expression is true. To fixe that you can do
a.sum() with (int'(item == 1))
Using the conditional operator achieves the same thing a little bit more cryptically because the bare numeric literals 1 and 0 are implicitly 32-bit signed decimal numbers. And that becomes the return datatype of the with {} clause.
.