Advertisement
NLinker

Adders

May 24th, 2018
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.69 KB | None | 0 0
  1. fn main() {
  2.     println!("{}", make_adder(1)(2));
  3.     println!("{}", make_adder(2)(3));
  4.     let indent = "xxx".to_owned();
  5.     let f = make_str_adder(&indent);
  6.     println!("add = {}", f("_abc_"));
  7. }
  8.  
  9. fn make_adder(a: i32) -> Box<Fn(i32) -> i32> {
  10.     if a == 1 {
  11.         Box::new(move |b| a + b)
  12.     } else {
  13.         Box::new(move |b| a * b)
  14.     }
  15. }
  16.  
  17. fn make_str_adder<'a>(a: &'a str) -> Box<Fn(&str) -> String + 'a> {
  18.    if a.chars().all(|c| c.is_ascii_whitespace()) {
  19.        Box::new(move |l| String::from(l))
  20.    } else {
  21.        Box::new(move |l| {
  22.            let mut r = String::new();
  23.            r.push_str(a);
  24.            r.push_str(l);
  25.            r
  26.        })
  27.    }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement