Created
October 26, 2018 21:29
-
-
Save rust-play/69e4701b5ea779a294609e13c40c1a70 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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(cell_update)] | |
use std::fmt::Display; | |
use std::cell::Cell; | |
pub trait IO: Sized { | |
type Output; | |
fn exec(self) -> Self::Output; | |
} | |
pub trait IOExt : IO { | |
fn seq<T: IO>(self, next: T) -> Seq<Self, T>; | |
fn and_then<T: IO, F: FnOnce(Self::Output)->T>(self, next: F) -> AndThen<Self, F::Output, F>; | |
} | |
impl <I: IO> IOExt for I { | |
fn seq<T: IO>(self, next: T) -> Seq<Self, T> { | |
Seq(self, next) | |
} | |
fn and_then<T: IO, F: FnOnce(Self::Output)->T>(self, next: F) -> AndThen<Self, F::Output, F> { | |
AndThen(self, next) | |
} | |
} | |
#[derive(Clone)] | |
pub struct Seq<T: IO, U: IO> (T, U); | |
impl <T: IO, U: IO> IO for Seq<T, U> { | |
type Output = U::Output; | |
fn exec(self) -> U::Output { | |
self.0.exec(); | |
self.1.exec() | |
} | |
} | |
#[derive(Clone)] | |
pub struct AndThen<T: IO, U: IO, F: FnOnce(T::Output)->U> (T, F); | |
impl <T: IO, U: IO, F: FnOnce(T::Output)->U> IO for AndThen<T, U, F> { | |
type Output = U::Output; | |
fn exec(self) -> U::Output { | |
self.1(self.0.exec()).exec() | |
} | |
} | |
struct While<U: IO<Output=bool> + Clone> (U); | |
impl <U: IO<Output=bool> + Clone> IO for While<U> { | |
type Output = (); | |
fn exec(self) { | |
if self.0.clone().exec() { | |
self.exec() | |
} | |
} | |
} | |
#[derive(Clone)] | |
struct Print<T: Display>(T); | |
struct Return<T> (T); | |
#[derive(Clone)] | |
struct Func<T, F: FnOnce()->T>(F); | |
impl <T: Display> IO for Print<T> { | |
type Output = (); | |
fn exec(self) { | |
println!("{}", self.0); | |
} | |
} | |
impl <T> IO for Return<T> { | |
type Output = T; | |
fn exec(self) -> T{ | |
self.0 | |
} | |
} | |
impl <T, F: FnOnce()->T> IO for Func<T, F> { | |
type Output = T; | |
fn exec(self) -> T{ | |
(self.0)() | |
} | |
} | |
fn main() { | |
let i = Cell::new(5); | |
Print("Hello world") | |
.seq(While( | |
Func(|| i.update(|x| x-1)) | |
.and_then(Print) | |
.seq(Func(|| i.get() > 0)))) | |
.exec() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment