Skip to content

Instantly share code, notes, and snippets.

@phaylon
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phaylon/f691618ff1c3e97dfe11 to your computer and use it in GitHub Desktop.
Save phaylon/f691618ff1c3e97dfe11 to your computer and use it in GitHub Desktop.
General closure operations for all types
trait ApplyClosure {
fn tangent<'a>(mut self, op: |&mut Self|) -> Self {
op(&mut self);
self
}
fn apply<R>(self, op: |Self| -> R) -> R {
op(self)
}
}
impl<T> ApplyClosure for T {}
fn main() {
let res = vec![2u, 3, 4]
.tangent(|v| println!("vec {}", v))
.iter()
.fold(0u, |a, n| a + *n)
.tangent(|s| println!("sum {}", s))
.apply(|n| n * 2);
println!("res {}", res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment