Skip to content
code0.HDL

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

  1. Read the argument type. A Tuple2 has exactly one shape, so there is no alternative to choose between, only fields to name.
  2. Read the result type and compare widths: two four-bit fields fill eight bits with nothing left over.
  3. Read the call in mkTop. It passes 4'ha first and 4'h5 second, 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 match assignment 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'ha5 matches 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.

Review this concept
Ready
Main.bsv