Created
January 24, 2019 09:17
-
-
Save lthms/9f2d632f69325d2838939bad724b057d 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
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