3 ms·
When I tried to be more functional, it was really awkward in Rust I wanted to write some helper functions that applied an argument to a closure and I got this
by iopq 4y ago
When I tried to be more functional, it was really awkward in Rust
I wanted to write some helper functions that applied an argument to a closure and I got this code
fn apply<A, B, C, G>(mut f: impl FnMut(B) -> G, a: A) -> impl FnMut(&B) -> C
// must still be `for<'r> impl FnMut(&'r B) -> C`, because that’s what filter requires
where
G: FnMut(A) -> C,
B: Copy, // for dereferencing
A: Clone,
{
move |b| f(*b)(a.clone()) // this must do any bridging necessary to satisfy the requirements
}
needless to say, Rust doesn't do automatic currying or any advanced functional language tricks so it's just painful to write the same type of code
- ekidd 4y agoYeah, your functional programming skills will probably be most useful at the achitectural level in Rust. Because mutation is very local in Rust, your individual functions can often get away with being imperative, but your overall architecture can't really rely on unrestrained mutation. But if we zoom in from the architecture to the individual lines of code, Rust is more of a mix of functional and imperative styles. Rust's iterators can be fairly pleasant for working with lazy streams. Closures are more of a mixed bag. This is partly because closures need to worry about ownership, which complicates things by splitting closures up into Fn, FnOnce and FnMut. And each closure is a separate anonymous type. So, yeah, Rust supports quite a few useful things with closures. But as your example shows, the type declarations can quickly become intolerable. So my strategy is to go with the flow, and keep things simple. I only bring out the heavy type declarations on special occasions, when they provide a big payoff. Otherwise I keep things as simple and boring and concrete as I can. There are a few popular Rust libraries which make very heavy use of generics. I find that this sometimes backfires, making those libraries slower to compile and harder for me to understand.