✨ iterated fn + defer + retry
This commit is contained in:
parent
c010cc13e8
commit
18c663fcdb
11 changed files with 678 additions and 65 deletions
67
examples/iterated.rs
Normal file
67
examples/iterated.rs
Normal file
|
@ -0,0 +1,67 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use comrade::iterated::{FunctionContext, IteratedFunction};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct AccFnContext {
|
||||
pub iter: u64,
|
||||
pub acc: u64,
|
||||
}
|
||||
|
||||
pub fn multiply_iterated(
|
||||
mut ctx: FunctionContext<AccFnContext, (u64, u64), u64>,
|
||||
) -> FunctionContext<AccFnContext, (u64, u64), u64> {
|
||||
// init
|
||||
let (a, b) = ctx.initial;
|
||||
|
||||
// end condition (return)
|
||||
if b == ctx.context.iter {
|
||||
ctx.done(ctx.context.acc);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// computation
|
||||
println!("doing calc {}", ctx.context.acc);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let val = ctx.context.acc + a;
|
||||
|
||||
// saving state
|
||||
ctx.state(|x| {
|
||||
x.iter += 1;
|
||||
x.acc = val;
|
||||
});
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
let f: IteratedFunction<AccFnContext, (u64, u64), u64> =
|
||||
IteratedFunction::new(multiply_iterated);
|
||||
|
||||
let x = f.run_to_end((5, 4));
|
||||
println!("computed x -> {x}");
|
||||
|
||||
// async
|
||||
let f = IteratedFunction::new_threaded(multiply_iterated, (5, 5));
|
||||
println!("This is running");
|
||||
println!("result is {}", f.output());
|
||||
|
||||
let f = IteratedFunction::new_threaded(multiply_iterated, (5, 50));
|
||||
|
||||
// pause the function
|
||||
f.pause();
|
||||
|
||||
// stop the function and get state
|
||||
let state = f.stop();
|
||||
println!("This was running");
|
||||
println!("state is {state:?}");
|
||||
|
||||
println!("reviving function");
|
||||
// continue with previous computed state
|
||||
let f = IteratedFunction::new_threaded_from_state(multiply_iterated, state);
|
||||
|
||||
// get output
|
||||
println!("result is {}", f.output());
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue