Skip to content

Instantly share code, notes, and snippets.

@lthms
Created January 24, 2019 09:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lthms/9f2d632f69325d2838939bad724b057d to your computer and use it in GitHub Desktop.
Save lthms/9f2d632f69325d2838939bad724b057d to your computer and use it in GitHub Desktop.
trait Func<A, B> {
fn apply(&self, x: A) -> B;
}
pub struct Curry<A, B>(Box<Fn(A) -> B>);
impl<A, B> Func<A, B> for Curry<A, B> {
fn apply(&self, x: A) -> B {
(self.0)(x)
}
}
// A -> B -> C === Curry<A, <Curry<B, C>>
// A -> B -> C -> D === Curry<A, <Curry<B, <Curry <C, D>>
macro_rules! func {
($x:ident => $blk:block) => {
Curry(Box::new(move |$x| {
$blk
}))
}
}
fn main() {
let test: Curry<u32, Curry<u32, u32>> = func!(x => {
func!(y => {
x + y
})
});
let pa = test.apply(2);
println!("{}", pa.apply(3));
println!("{}", pa.apply(5));
println!("{}", test.apply(3).apply(4));
println!("{}", test.apply(3).apply(4));
let x: Box<Fn(u32) -> u32> = Box::new(|x| x + 1);
let x: Box<Any> = Box::new(x);
println!("{}", x.downcast_ref::<Box<Fn(u32) -> u32>>().unwrap()(2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment