Skip to content

Instantly share code, notes, and snippets.

@tilpner
Last active September 30, 2023 10:41
Show Gist options
  • Save tilpner/28c962eb9f1eb8cbeb35 to your computer and use it in GitHub Desktop.
Save tilpner/28c962eb9f1eb8cbeb35 to your computer and use it in GitHub Desktop.
Macro for inline definition of anonymous functions, and examples of passing functions.
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