Chaining Methods

Objective: Demonstrate how to chain methods commonly used in functional programming.

Python

data = [2, 3, 7, 4, 1]
sqr = map(lambda x: x**2, data)
lim = filter(lambda x: x < 20, sqr)
res = sum(lim)
print(res)

Alternatively we can use generator-expressions (or list comprehensions):

data = [2, 3, 7, 4, 1]
sqr = (x**2 for x in data)
lim = (x for x in sqr if x < 20)
res = sum(lim)
print(res)

Rust

fn main() {
    let data = [2, 3, 7, 4, 1];
    let res = data.iter()
                .map(|x: &i32| x.pow(2))
                .filter(|x| x < &20)
                .sum::<i32>();
                
    println!("{:?}", res);
}

Alternatively:

fn main() {
    let data: Vec<i32> = vec![2, 3, 7, 4, 1];
    let res: i32 = data.iter()
                .map(|x| x.pow(2))
                .filter(|x| x < &20)
                .sum();
                
    println!("{:?}", res);
}

Alternatively crate cute can be used to mimic comprehension-like style:

#[macro_use(c)]
extern crate cute;

fn main() {
    let data: Vec<i32> = vec![2, 3, 7, 4, 1];
    let sqr = c![x.pow(2), for x in data];
    let lim = c![x, for x in sqr, if x < 20];
    let res: i32 = lim.iter().sum();
    dbg!(res);
}

Crystal

data = [2, 3, 7, 4, 1]
puts data.map { |x| x**2 }
  .select { |x| x < 20 }
  .sum

Alternatively:

data = [2, 3, 7, 4, 1]
puts data.map(&.** 2).select(&.< 20).sum