Converting loop to mostly non-mutable code [functional programming]

Hey guys, I have a loop that pushes the factors of a number into an array/vector. Here’s the code in Rust:

fn main() {
  let mut v: Vec<i32> = Vec::new();
   while i <= num {
         i += 1;
         if num % i == 0 {
             v.push(i);
         };
     }
     println!("{}", v)
}

For those who don’t understand rust, here’s a Javascript simulacrum;

let v = [];
for(let i = 1; i <= num; i++) {
    if(num % i == 0) {
        v.push(i);
    }
}

In pseudocode:

  • Declare a number.
  • Begin looping through every whole positive number before this number
  • If the loop number and the original number are divisible with no remainder, push it to a vector/array.

Now, this isn’t optimal - the resultant collection v is being manipulated. If I wanted to convert this into functional code, how would I avoid repeatedly changing v? This is one thing I considered:

  • If the number has a remainder of 0:
    • Make a vector out of the number
    • When another factor is found, make a vector out of the new number and the elements of the old vector

Any thoughts? I’m relatively new to nonmutable/functional programming and thought this would be a nice way to get into it.

1 Like

Use collect https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect to sweep the actual mutable pushing under a rug.

1 Like

Thanks wh0! Once again you prove yourself the genius of geniuses.

3 Likes

Actually, I’m not quite sure I understand. How should I collect the variables? Should I be trying to get the factors in .map or .iter and then collecting it?

I’d suggest .filter for this case.

1 Like

Hum, I should familiarize myself with iterator methods. Thanks for the suggestion

function fn (num) {
  return [...Array(num + 1).keys()]
  	.filter(key => num % key == 0)
}
1 Like