DEV Community

Discussion on: Higher-Order Functions in Rust

Collapse
 
theodesp profile image
Theofanis Despoudis

I had the impression that map does not modify the original array but returns a new array with all the elements mapped to the function's domain. Also if you modify something in functional programming then it's unsafe and not really functional.

Can you show an example of this? (not using mut for example)?

Collapse
 
deciduously profile image
Ben Lovy • Edited

Definitely, good catch - map was probably a bad choice of name. This example is not a pure functional style, but higher-order functions do not need to be pure. I thought that example was more interesting - if you do need a pure map I generally recommend using the standard library. I'd argue the above functions are still "functional programming", just not "pure functional programming". I don't know that I'd call it unsafe - fearless mutation like this is more idiomatic Rust.

I'll write up an example later this morning once I've had some coffee!

Collapse
 
deciduously profile image
Ben Lovy

I've implemented pure versions of map_rows, map_rows2, and make_incrementer - here's an updated Playground link.

The signatures are almost the same - I've just replaced &mut Grid with &[Vec<i32>]. The only difference is the body of the functions themselves but you're correct - this set adheres more strictly to a functional paradigm whereas the originals do not.

Collapse
 
myrrlyn profile image
Alexander Payne

Rust isn’t functional; it’s just dressed like it. The ownership rules allow the compiler to prove that mut self -> Self functions and &mut self -> () methods are wholly equivalent, and therefore eliminate the need to construct a new object and destroy the old.