37Implementation
Destructure two tuple fields
Problem
joinFields receives a Tuple2 of two four-bit values and must return them
concatenated in tuple order: the first field becomes the upper nibble and the
second the lower nibble. The starter ignores its argument and returns 8'h00,
so the public run prints joined = 00 instead of a5.
Edit only the body of joinFields, and bind the fields with a match
assignment. Keep the signature and mkTop unchanged.
Read and predict
- Read the argument type. A
Tuple2has exactly one shape, so there is no alternative to choose between, only fields to name. - Read the result type and compare widths: two four-bit fields fill eight bits with nothing left over.
- Read the call in
mkTop. It passes4'hafirst and4'h5second, values chosen to be easy to tell apart.
Before pressing Run, predict the starter's output (00) and the output
after a correct repair. Decide which input field ends up in which half.
Make the repair
First destructure, then rebuild. One match statement introduces one fresh name
per tuple position. The next statement forms the result from those names. The
two steps are independent decisions: the pattern fixes what each name means,
and the result expression fixes where each name goes.
Run again and confirm the new output. Then explain why swapping the two names
in the result, without touching the pattern, would print 5a.
Completion contract
- A
matchassignment with a tuple pattern binds both fields. - The first field is the upper nibble and the second is the lower nibble, for every pair of inputs.
- Equal fields, zero fields, and all-ones fields keep their positions.
- Returning
8'ha5matches only the visible sample.
Progressive hints
Hint 1: why match fits
A match assignment binds typed variables for the statements that follow it,
without selecting a case arm. It suits tuples and structs whose shape is
already fixed.
Hint 2: build the pattern
Count the tuple positions and write a tuple pattern with one fresh pattern variable in each position.
Hint 3: rebuild the result
Compare each bound width with the halves of Bit#(8). A bit concatenation of
the two names, in tuple order, has exactly the result width.
Transfer experiment
Swap the result halves while keeping the pattern unchanged. Predict the new output before running, then restore the required order.