1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::fmt;
use error_stack::{Context, IntoReport, Report, Result, ResultExt};
#[derive(Debug)]
struct ParseExperimentError;
impl fmt::Display for ParseExperimentError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("invalid experiment description")
}
}
impl Context for ParseExperimentError {}
fn parse_experiment(description: &str) -> Result<(u64, u64), ParseExperimentError> {
let value = description
.parse()
.report()
.attach_printable_lazy(|| format!("{description:?} could not be parsed as experiment"))
.change_context(ParseExperimentError)?;
Ok((value, 2 * value))
}
#[derive(Debug)]
struct ExperimentError;
impl fmt::Display for ExperimentError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("Experiment error: Could not run experiment")
}
}
impl Context for ExperimentError {}
fn start_experiments(
experiment_ids: &[usize],
experiment_descriptions: &[&str],
) -> Result<Vec<u64>, ExperimentError> {
let experiments = experiment_ids
.iter()
.map(|exp_id| {
let description = experiment_descriptions.get(*exp_id).ok_or_else(|| {
Report::new(ExperimentError)
.attach_printable(format!("Experiment {exp_id} has no valid description"))
})?;
let experiment = parse_experiment(description)
.attach_printable(format!("Experiment {exp_id} could not be parsed"))
.change_context(ExperimentError)?;
Ok(move || experiment.0 * experiment.1)
})
.collect::<Result<Vec<_>, ExperimentError>>()
.attach_printable("Unable to setup experiments")?;
Ok(experiments.iter().map(|experiment| experiment()).collect())
}
fn main() -> Result<(), ExperimentError> {
let experiment_ids = &[0, 2];
let experiment_descriptions = &["10", "20", "3o"];
start_experiments(experiment_ids, experiment_descriptions)?;
Ok(())
}