mutable/vector Tutorial
Small Case: Score A Candidate With A Working Copy
moonbit
///|
fn score_candidate(
raw_features : @mutable.Vector[Int],
weights : @mutable.Vector[Int],
) -> Int {
let working = raw_features.copy()
working.map_inplace(fn(x) { x + 1 })
working.left_scale_inplace(2)
working.dot(weights)
}
///|
test "mutable vector tutorial case" {
let raw = @mutable.Vector::from_array([1, 2, 3])
let weights = @mutable.Vector::from_array([3, 4, 5])
let score = score_candidate(raw, weights)
inspect(raw, content="|1, 2, 3|")
inspect(score, content="76")
}This is a solid mutation-oriented pattern:
- Keep the caller-facing vector unchanged.
- Take a
copy()as a working buffer. - Perform normalization and scaling with
map_inplaceandleft_scale_inplace. - Finish with
dotonce the vector is ready for scoring.
Suggested Flow
- Create vectors with
Vector::from_array,Vector::make, orVector::makei. - Use
v[i]andv[i] = xfor direct element access. - Use
map_inplace,left_scale_inplace, andright_scale_inplacewhen mutation is intended. - Use
dot,lin_comb,tensor_product,to_row_matrix, andto_col_matrixwhen the vector participates in larger algebraic or matrix-building work.
Practical Guidance
- Use non-
inplacehelpers when you need a fresh vector instead of modifying the original. - Call
copy()before mutating when a caller still needs the previous value. - Reach for
dot,lin_comb, and matrix-conversion helpers once the vector is participating in a larger numerical workflow.