exowos/subject_text/vec/access.md
2025-03-12 00:15:24 +01:00

1.6 KiB

name = "Accessing values" file = "src/vec/access.rs"
name = "Accessing values" file = "src/vec/access.rs"

Instead of using the good old C-style bound checking:

if vec.len() < 1 {
    return None;
} else {
    // compiler still thinks this line can panic
    return vec[0];
}

Try to implement these functions using non-panicking methods like last, last_chunk, or get.

/// Add the last two numbers of the input slice.
///
/// # Return value
/// `None` if the slice is not large enough
/// `Some(result)` if the slice has at least 2 elements
pub fn add_last_two(v: &[f32]) -> Option<f32> {
    unimplemented!()
}

/// Duplicate the top element from the stack if it exist
/// (the stack is represented as a Vec with top == last)
///
/// # Return value
/// `Some(())` if the operation succeeded
/// `None` if not
pub fn dup_top(v: &mut Vec<f32>) -> Option<()> {
    unimplemented!()
}

/// Compute the median of a slice in place (if the slice was sorted, it would be the middle element)
pub fn median(v: &[i32]) -> Option<i32> {
    unimplemented!()
}
fn main() {
    assert_eq!(add_last_two(&[]), None);
    assert_eq!(add_last_two(&[10.0]), None);
    assert_eq!(add_last_two(&[1.0, 2.0, 3.0]), Some(5.0));

    let mut stack = vec![1.0];
    assert!(dup_top(&mut stack).is_some());
    assert_eq!(&stack, &[1.0, 1.0]);

    stack.clear();
    assert!(dup_top(&mut stack).is_none());

    assert_eq!(median(&[2, 1, 3]), Some(2));
}