Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using fold vs sum in *Higher Order Functions* #1447

Closed
alexfertel opened this issue Jul 2, 2021 · 0 comments · Fixed by #1560
Closed

Using fold vs sum in *Higher Order Functions* #1447

alexfertel opened this issue Jul 2, 2021 · 0 comments · Fixed by #1560

Comments

@alexfertel
Copy link
Contributor

I noticed that the example comparing imperative vs functional approaches uses fold vs sum.

One can argue that fold is classically thought of as functional, but I think that the objective of the example is the functional flavor, thus sum would be more appropriate.

    let sum_of_squared_odd_numbers: u32 =
        (0..).map(|n| n * n)                             // All natural numbers squared
             .take_while(|&n_squared| n_squared < upper) // Below upper limit
             .filter(|&n_squared| is_odd(n_squared))     // That are odd
             .fold(0, |acc, n_squared| acc + n_squared); // Sum them

vs

    let sum_of_squared_odd_numbers: u32 =
        (0..).map(|n| n * n)                             // All natural numbers squared
             .take_while(|&n_squared| n_squared < upper) // Below upper limit
             .filter(|&n_squared| is_odd(n_squared))     // That are odd
             .sum();                                     // Sum them
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants