Last active
March 11, 2016 00:07
-
-
Save myzone/08d24f1c96083f9af725 to your computer and use it in GitHub Desktop.
Behavior
This file contains 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
mod behavior { | |
pub trait Behavior { | |
type T; | |
type S; | |
type R: IntoIterator<Item=Self::S>; | |
fn apply(&self, &Self::T, &Self::S) -> Self::T; | |
fn react(&self, &Self::T, &Self::S) -> Self::R; | |
} | |
pub struct Executor<'l, T: 'l + Behavior> { | |
behavior: &'l T, | |
} | |
impl<'l, T: 'l + Behavior> Executor<'l, T> { | |
pub fn new(behavior: &'l T) -> Executor<'l, T> { | |
Executor { behavior: behavior } | |
} | |
pub fn apply<I: IntoIterator<Item = T::S>>(&self, initial_state: T::T, signals: I) -> T::T { | |
signals.into_iter() | |
.fold(initial_state, |state, signal| { | |
let reaction = self.behavior.react(&state, &signal); | |
let next_state = self.behavior.apply(&state, &signal); | |
self.apply(next_state, reaction) | |
}) | |
} | |
} | |
} | |
mod transform { | |
pub trait Value<T> { | |
fn map<K, F: FnOnce(T) -> K>(self, f: F) -> K; | |
fn with<F: FnOnce(&T)>(self, f: F) -> T; | |
fn with_mut<F: FnOnce(&mut T)>(mut self, f: F) -> T; | |
} | |
impl<'l, T: 'l> Value<T> for T { | |
fn map<K, F: FnOnce(T) -> K>(self, f: F) -> K { | |
f(self) | |
} | |
fn with<F: FnOnce(&T)>(self, f: F) -> T { | |
f(&self); | |
self | |
} | |
fn with_mut<F: FnOnce(&mut T)>(mut self, f: F) -> T { | |
f(&mut self); | |
self | |
} | |
} | |
} | |
fn main() { | |
use behavior::*; | |
use transform::*; | |
struct SimpleBehavior; | |
impl Behavior for SimpleBehavior { | |
type T = i32; | |
type S = i32; | |
type R = Vec<i32>; | |
fn apply(&self, state: &i32, signal: &i32) -> i32 { | |
*state + *signal | |
} | |
fn react(&self, _: &i32, _: &i32) -> Vec<i32> { | |
vec![] | |
} | |
} | |
let r = SimpleBehavior.map(|behavior| { | |
let executor = Executor::new(&behavior); | |
executor.apply(5, vec![10, 11]) | |
}); | |
println!("{:?}", r); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment