30Implementation
Count set bits with control flow
Situation and starter reading
countOnes must return the number of set bits in an eight-bit input. The
starter compiles, but the function initializes count and immediately returns
it without reading value.
Read the function signature first: a four-bit result can represent every count
from zero through eight. Then read the three calls in mkTop; they exercise a
mixed byte, an all-one byte, and an all-zero byte. Edit only the body of
countOnes. Treat its signature and the observation rule in mkTop as fixed.
Predict before editing
Run the starter mentally before pressing Run. Since no expression depends on
value, all three calls report zero. Compilation succeeds because the code is
type-correct; this is a behavioral defect, not a syntax or type error.
For the repair, maintain this invariant: after processing index i, count
equals the number of one bits seen from index 0 through i. A constant-bounded
loop controls how much logic is generated, while the if tests runtime input.
The accumulator uses local = assignment, so the function remains
combinational rather than becoming an eight-cycle machine.
Required change and observable completion
- Examine exactly indices 0 through 7 with an
Integerloop variable and constant bounds. - Increase
countonly when the selected bit is one. - Preserve the function signature and surrounding module.
Run is observably correct when the mixed sample reports five, the all-one sample reports eight, and the all-zero sample remains zero. The implementation must also work for other bit patterns; hard-coding those three results does not satisfy the function contract.
Progressive hints
Hint 1: establish the trace
Write the accumulator values for the first two indices of the mixed sample. The value changes only when the selected bit is one.
Hint 2: choose static structure
Place one for loop between initialization and return. Its declaration needs
an Integer index, a constant starting point, a constant stopping boundary,
and a one-step update.
Hint 3: choose the assignment model
Use the index to select one input bit. Guard the accumulator update with an
if, and use local variable assignment rather than the register-write
operator.
Transfer experiment
After completion, temporarily invert the tested condition so the same loop counts zero bits. Predict the new three results and explain why each new count plus the original count equals eight. Restore the set-bit version afterward.