Search code examples
arraysrustnested-listsheterogeneous-array

Rust special array


I want to define function that takes one argument which is "special" array, like in example below:

[5, 2, [7, -1], 3, [6, [-13, 8], 4]]

This array is a non-empty array that contains either integers or other "special" arrays.

What should be the proper argument type of the function that receives such "special" array?


Solution

  • You cannot give an array like that as a parameter to a function, because it is ot homogeneous. However, you can define your own type of special array.

    The following code shows how to encode a special array [2, [2, 2]]:

    #[derive(Debug)]
    enum Special {
        Integer(i32),
        Vector(Vec<Special>)
    }
    
    fn main() {
        let special = Special::Vector(
            vec![Special::Integer(2), 
            Special::Vector(vec![Special::Integer(2), Special::Integer(2)])]
        );
        println!("{:?}", special);
    }
    

    You can use pattern matching to check on which kind of enum element you have in the array, either an Integer or a Vector:

    match special {
        Special::Integer(val) => println!("I am an integer: {}", val),
        Special::Vector(vec) => println!("I have nested element inside: {:?}", vec)
    }
    

    To iterate through such an array you need a function that can evaluate reccursively, because the Vector arm has nestef elements. We can define a function that evals reccursively as such:

    fn eval(special: Special) {
        match special {
            Special::Integer(val) => println!("Integer met {}", val),
            Special::Vector(vec) => vec.into_iter().for_each(|special_elem| eval(special_elem))
        }
    }
    

    One thing worth noticing is that since we capture by value, we cause a move, so we can safely use into_iter to make sure we consume all the values.