Skip to content

Instantly share code, notes, and snippets.

@jeremy-w
Last active August 29, 2015 14:27
Show Gist options
  • Save jeremy-w/2cd303779bc3c8607da8 to your computer and use it in GitHub Desktop.
Save jeremy-w/2cd303779bc3c8607da8 to your computer and use it in GitHub Desktop.
Implements Elixir's |> for Rust as pipe!.
/*
* Compile with:
* rustc -Z unstable-options --pretty expanded pipe.rs
*/
/* @file pipe.rs
* @author Jeremy W. Sherman (GitHub: @jeremy-w)
* @license ISC
*
* Implements and demonstrates use of the "pipe" (aka "thread-first") macro.
*/
/*
Copyright (c) 2015, Jeremy W. Sherman
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
// trace_macros is behind a feature gate.
// Good luck finding something to explain what that means
// concretely for a newb!
//#![feature(trace_macros)]
/// Directly substitutes in its argument.
/// Somehow avoids an error in the base case of `pipe!`.
macro_rules! result {
($e:expr) => { $e };
}
/// Threads an expression as the first argument to the following
/// function. Analogous to Elixir's `|>` and Clojure's `->`.
///
/// # Examples
/// ```
/// pipe! { 1 , plus(2) , plus(3) }
/// => thread the 1 into the plus(2)
/// pipe! { plus(1, 2) , plus(3) }
/// => thread the plus(1, 2) into the plus(3)
/// plus( plus(1, 2) , 3 )
macro_rules! pipe {
($e:expr, $func:ident ( $($args:tt)* )) => {
/* For whatever reason, when I don't wrap this in result!,
* I get error:
*
* pipe.rs:17:21: 17:26 error: unexpected token: `3`
* pipe.rs:17 $func($e, $($args)*)
* ^~~~~
*/
result!($func($e, $($args)*))
};
($e:expr, $func:ident ( $($args:tt)* ), $($rest:tt)*) => {
pipe!($func($e, $($args)*), $($rest)*)
};
}
fn plus(x: i32, y: i32) -> i32 {
return x + y;
}
fn main() {
//trace_macros!(true);
let result = pipe!
{ 1
, plus(2)
, plus(3)
};
println!("{}", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment