-
-
Save tilpner/28c962eb9f1eb8cbeb35 to your computer and use it in GitHub Desktop.
Macro for inline definition of anonymous functions, and examples of passing functions.
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
fn once(f: Box<Fn()>) { f() } | |
fn twice(f: fn()) { f(); f() } | |
fn thrice<F: Fn()>(f: F) { f(); f(); f() } | |
// Inline definition of anonymous functions. Examples: | |
// l!(42;) | |
// l!(i32 := 42) | |
// l!(i: i32 := i + 42) | |
// l!(i: i32, j: i32 -> i32 := i + j) | |
macro_rules! l { | |
($body: expr) => ({ fn f() { $body } f }); | |
($res: ty := $body: expr) => ({ fn f() -> $res { $body } f }); | |
($($n: ident: $t: ty),+ := $body: expr) => ({ | |
fn f($($n: $t),+) { $body } f | |
}); | |
($($n: ident: $t: ty),+ -> $res: ty := $body: expr) => ({ | |
fn f($($n: $t),+) -> $res { $body } f | |
}) | |
} | |
fn main() { | |
once(Box::new(|| println!("Once!"))); | |
twice(l!(println!("Twice!"))); | |
thrice(|| println!("Thrice!")); | |
let inc = l!(i: i32 -> i32 := i + 1); | |
println!("{}", inc(inc(40))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment