-1

I have an input:

let b = String::from("1 2 4 5 6");

And my task is to return the exponential function of each value as a string as output:

let output = "2.718281828459045 7.38905609893065 54.598150033144236 148.4131591025766 403.4287934927351";

I have no idea how to solve this task. How to parse each value and use exp function and send string of the result?

kmdreko
  • 42,554
  • 6
  • 57
  • 106

2 Answers2

5

Here's the ingredients:

phimuemue
  • 34,669
  • 9
  • 84
  • 115
2

I'm not going to repeat what phimuemue has already explained so here's an implementation:

fn example(s: &str) -> String {
    s.trim()
        .split_whitespace()
        .map(|n| {
            let mut n = n.parse::<f64>().unwrap();
            n = n.exp();
            n.to_string()
        })
        .collect::<Vec<String>>()
        .join(" ")
}

fn main() {
    let input = String::from("1 2 4 5 6");
    let output = example(&input);
    dbg!(output); // "2.718281828459045 7.3890560989306495 54.59815003314423 148.41315910257657 403.428793492735"
}

playground

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
  • Or using [`Itertools::join`](https://docs.rs/itertools/0.10.0/itertools/trait.Itertools.html#method.join): https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ce539a2fbc815184fe85c1488c84f60e – Jmb Feb 16 '21 at 14:37
  • It would be more helpful to demonstrate how to propagate the result, rather than `.unwrap()`ing it and potentially panicking on a bad input. – dimo414 Dec 01 '22 at 07:33