Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Vec<Vec<f64>> into a string

I am new to Rust, and I am struggling with a simple task. I'd like to convert a matrix into a string, with the fields separated by tabs. I think this is possible by using the map function or something similar, but right now whatever I try gives me an error.

This is what I have, and I'd like to convert the col part into function, which returns a tab separated string, which I can print. In Python this is something like row.join("\t"). Is there something similar in Rust?

fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec.iter() {
        for col in row.iter() {
           print!("\t{:?}",col);
        }
        println!("\n");
    }
}
like image 464
Mandragor Avatar asked Dec 18 '22 18:12

Mandragor


2 Answers

There is indeed a join in the standard library, but it's not super useful (often additional allocation is required). But you can see a solution here:

fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec {
        let cols_str: Vec<_> = row.iter().map(ToString::to_string).collect();
        let line = cols_str.join("\t");
        println!("{}", line);
    }
}

The problem is that this join works with slices and not with iterators. We have to convert all elements into a string first, collect the result in a new vector and can use join then.

The crate itertools defines a join method for iterators and can be applied like so:

for row in vec {
    let line = row.iter().join("\t");
    println!("{}", line);
}

And to avoid using any of the named functionality, you can of course do it manually:

for row in vec {
    if let Some(first) = row.get(0) {
        print!("{}", first);            
    }
    for col in row.iter().skip(1) {
        print!("\t{}", col);
    }
    println!("");
}
like image 55
Lukas Kalbertodt Avatar answered Jan 08 '23 02:01

Lukas Kalbertodt


Besides join from itertools you could always use fold on iterator (which is really useful), like this:

row.iter().fold("", |tab, col| { print!("{}{:?}", tab, col); "\t" });
like image 21
swizard Avatar answered Jan 08 '23 02:01

swizard