Last active
February 23, 2017 22:00
-
-
Save DavidEichmann/0c7716836412cfbb7c45b2b78249a829 to your computer and use it in GitHub Desktop.
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
#![feature(conservative_impl_trait)] | |
use std::marker::PhantomData; | |
use std::collections::HashMap; | |
fn main() { | |
let sum_arr = | |
state::<i32, i32, i32, _>(0, | |
// ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `for<'a> impl Arr<(_, _), _>: Arr<(&'a {integer}, _), ({integer}, _)>` is not satisfied | |
arr::<(&i32, i32), (i32, i32), _>(|(s, x)| (s + x, s + x))); | |
println!("{:?}", sum_arr.push(1)); | |
println!("{:?}", sum_arr.push(1)); | |
println!("{:?}", sum_arr.push(2)); | |
println!("{:?}", sum_arr.push(2)); | |
println!("{:?}", sum_arr.push(3)); | |
println!("{:?}", sum_arr.push(3)); | |
} | |
pub trait Arr<In, Out> { | |
fn push(&mut self, input: In) -> Out; | |
} | |
struct FnMutArr<In, Out, F> | |
where F: FnMut(In) -> Out | |
{ | |
_marker: PhantomData<(In, Out)>, | |
f: F, | |
} | |
impl<In, Out, F> Arr<In, Out> for FnMutArr<In, Out, F> | |
where F: FnMut(In) -> Out | |
{ | |
fn push(&mut self, input: In) -> Out { | |
(self.f)(input) | |
} | |
} | |
pub fn arr<In, Out, F: FnMut(In) -> Out>(f: F) -> impl Arr<In, Out> { | |
FnMutArr { | |
_marker: PhantomData, | |
f: f, | |
} | |
} | |
pub fn state<State, In, Out, A>(initial_state: State, mut a: A) -> impl Arr<In, Out> | |
where A: for<'a> Arr<(&'a State, In), (State, Out)> | |
{ | |
let mut state = initial_state; | |
arr(move |input| { | |
let (new_state, out) = a.push((&state, input)); | |
state = new_state; | |
out | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment