Macro git_next_core::pike
source · macro_rules! pike { ($head:tt $(|> $funs_head:tt $(:: $funs_tail:tt)* $(! $($bang:tt)?)?)+) => { ... }; }
Expand description
The pipe operator |> allows you to establish “pipelines” of functions in a flexible manner.
use pike::pike;
fn times(a: u32, b: u32) -> u32{
a * b
}
fn times2(n: u32) -> u32 {
times(n, 2)
}
// Passes the preceding expression as the only argument of proceding function.
let num = pike! {
2
|> times2
|> times2
};
assert_eq!(num, 2 * 2 * 2);
// Passes the preceding expression as the first argument of proceding function.
// by wrapping the function in parentheses we can pass the remanining arguments by partially
// calling the `times` as `times(?, 2)` and passing 2 as its first argument via the pipeline.
let num = pike! {
1
|> (times(2))
|> (times(3))
};
assert_eq!(num, 1 * 2 * 3);
// call a method using pipelines
let len = pike!("abcd" |> str::len);
assert_eq!(len, "abcd".len());
// Closures can also be pipelined similar to partial functions.
let c = pike! {
['a', 'b', 'c', 'd']
|> (|it: [char; 4]| it[2])
};
assert_eq!(c, 'c');
// Piping through `&` symbol would get a reference to the preceding expression.
let it = "it";
let is_it = |r: &&str| it == *r;
let is_it = pike! (it |> & |> is_it);
assert_eq!(is_it, true);
// takes a string length, doubles it and converts it back into a string
let len = pike! {
"abcd"
|> str::len
|> (as u32)
|> (times(2))
|> &
|> u32::to_string
};
assert_eq!(len, "8");