3 ms·
> Whereas in the functional world, you’ll have to 4 different ‘.read’ function calls with an if statement. A good language for functional programming provides
by tomjakubowski 8y ago
> Whereas in the functional world, you’ll have to 4 different ‘.read’ function calls with an if statement.
A good language for functional programming provides parametric polymorphism via traits or typeclasses:
pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
}
impl Read for std::fs::File { /* ... */ }
impl Read for String { /* ... */ }
Then you can write a generic function like this:
pub fn read_kilobyte<R>(r: R) -> io::Result<Vec<u8>>
where R: std::io::Read {
let mut buf = vec![0u8; 1024]; // vector of 1024 0s
let nbytes = r.read(&mut buf[..])?;
buf.truncate(nbytes);
Ok(buf)
}
And call it like this:
let kb1 = read_kilobyte(File::open(...)?)?;
let kb2 = read_kilobyte("foo bar baz quux".to_string())?;
No ifs in sight.
- nuclear_eclipse 8y agoThat looks an awful lot like OOP to me...
- jonreem 8y agoOne of the many difference is that there is no inheritance, and implementations of traits can be added for types long after they are defined. Traits in rust are not like java interfaces.
- magicalhippo 8y agoHow are traits specific to being a functional language rather than an OO language though? I mean, I don't see anything horribly functional-language-specific about your trait example.
- jonreem 8y agoIt wasn't my example, but it's just disproving the notion that FP somehow means you need to write big if statements to dispatch your functions. Traits are not functional-language specific except in that they are often used in FP to solve problems similar to those one might use inheritance to solve in OOP.