Skip to content

Instantly share code, notes, and snippets.

@de-sh
Last active June 19, 2020 16:36
Show Gist options
  • Save de-sh/c0a3d026ff9f2680bdb76da7e1b79332 to your computer and use it in GitHub Desktop.
Save de-sh/c0a3d026ff9f2680bdb76da7e1b79332 to your computer and use it in GitHub Desktop.
Summing a vector into a single value

The syntax of rust is readability driven and there is immense attention to detail given on simple interfaces to achieve functional programming approach of computation with map, filter and fold allowing for an iter item to be operated on, which sometimes increases the readability of the program in question.

Introducing Closures

A closure is the concept of isolating the values that a function is operating on, it's 'environment', popularized in functional programming. We are using an anonymous function in our program, which is passed literally as a value instead of being a call. To define an anonymous function, closure in rust we are going to use the | operator and place the arguments between it, before defining the function's behaviour right after.

let inc = |i| i+1;
println!("{}", inc(1));

Run in Playground

To achieve summing of a set of values we are considering an iterator over the memory locations specified by the Vec<i16> storing those numbers, it is passed to sum(). The iterator is generated by calling the .iter() on the vector, we are to operate on this iterator with the functional approach that programmers familiar with JS and Python will know of as reduce, rust-lang refers to it as fold, since we are literally requiring it to fold together the contents of an iterable passed to it and generate a singular resultant value, the sum in this case. Let us see how we can achieve this. The functional part of the program is the use of a closure to define the operations to be performed on each and every value of the iterable.

let list: Vec<i16> = vec![1,2,3,4];
let sum: i64 = list.iter() // Generates the iterator
               .fold(0, |s, u| s + (*u as i64)); 
               // 'Folds' values of iterable into as per given closure

Run in Playground

Here we achieve the task of summing with the closure |s, u| s + (*u as i64), which cosiders the iterator allows the use of a value u by dereferencing which is first converted up into an i64(64 bit integer) before being added to the 'accumulator' s which is initially set to 0 by being passed in as the initial argument of fold().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment