Last active
January 13, 2022 13:32
-
-
Save AlexanderNenninger/3ce5f842d83a52abdb81ae5c489d0966 to your computer and use it in GitHub Desktop.
Callback to track time when last event occured. Written in Rust for referential transparency.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::boxed::Box; | |
type Callback<U, T> = Box<dyn Fn(&mut U, &T)>; | |
type Condition<U, T> = Box<dyn Fn(&U, &T) -> bool>; | |
type Effect<U, T> = Box<dyn Fn(&mut U, &T)>; | |
fn make_callback<U: 'static, T: 'static>( | |
condition: Condition<U, T>, | |
effect: Effect<U, T>, | |
) -> Callback<U, T> { | |
let cb = move |u: &mut U, t: &T| { | |
if condition(u, t) { | |
effect(u, t) | |
} | |
}; | |
Box::new(cb) | |
} | |
fn step(u: &mut [f64; 2], t: &mut f64, callback: &Callback<[f64; 2], f64>) { | |
callback(u, t); | |
*t += 1.; | |
u[0] *= 1.5; | |
} | |
fn main() { | |
let u = &mut [1., 0.]; | |
let t = &mut 0.; | |
let condition: Condition<[f64; 2], f64> = Box::new(|u: &[f64; 2], t: &f64| u[0] >= 3.); | |
let effect: Effect<[f64; 2], f64> = Box::new(|u: &mut [f64; 2], t: &f64| { | |
u[1] = *t; | |
u[0] = 0.1 | |
}); | |
let cb = make_callback(condition, effect); | |
for i in 1..20 { | |
step(u, t, &cb); | |
println!("u: [{0:.2}, {1:.2}], t: {2:.2}", u[0], u[1], t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment