3 ms·
I don't know that traits in Rust are an example of ad-hoc polymorphism, since they're fully type-safe.
by kibwen 10y ago
I don't know that traits in Rust are an example of ad-hoc polymorphism, since they're fully type-safe.
- burntsushi 10y agoI don't think that means it isn't ad hoc. Type classes in Haskell were originally introduced as a form of ad hoc polymorphism, for example: http://202.3.77.10/users/karkare/courses/2010/cs653/Papers/ad-hoc-polymorphism.pdf http://202.3.77.10/users/karkare/courses/2010/cs653/Papers/a... (One of Wadler's great papers btw, worth a read.) See also: https://en.wikipedia.org/wiki/Type_class https://en.wikipedia.org/wiki/Type_class Of course, Haskell type classes and Rust traits aren't the same. But they are quite similar!
- dllthomas 10y agoAs I understand the term, "ad-hoc polymorphism" refers to dispatch based on types (as opposed to "parametric polymorphism", where one code path works for any type). Nothing to do with type-safety.
- mmstick 10y agoHere's an example: `Stdin` and `File` both implement the `Read` trait. Therefore, you can write a function that takes the traits that you want to use as input parameters. fn do_something_with<S: Read>(source: S) { // do something with input source } Then you can do the following: let stdout = io::stdout(); do_something_with(stdout.lock()); let file = File::open(path).unwrap(); do_something_with(file); You're free to narrow down/expand the types/methods that can be used with the function if you add more traits.
- tatterdemalion 10y ago"ad-hoc polymorphism" is an informal term; traits are sort of both ad hoc and parametric. I've sometimes imagined someone writing a paper about specialization and naming it "How to make parametric polymorphism less parametric" after Wadler's paper.