5 ms·
C++ doesn't need type classes as it has more powerful overloading. this is valid C++14: template<typename A, typename B> auto add(A a, B b) {
by detrino 13y ago
C++ doesn't need type classes as it has more powerful overloading.
this is valid C++14:
template<typename A, typename B>
auto add(A a, B b)
{
return a + b;
}
- eru 13y agoCan overloading express parametricity?
- detrino 13y agoCan you give an example of what you mean?
- eru 13y agoE.g. the type of map is map :: forall a b. (a -> b) -> [a] -> [b] The important part here is the `forall'. This means, that Haskell guarantees that essentially the map function can not look at the elements of your list. The only way for map to produce a value of type `b' is to apply the given call-back on an `a'. So you know that `map' can not eg add up your `a's. Compare C++'s templates and overloading, where more function definitions with more specific types have precedence over more general ones. See the first answer of https://stackoverflow.com/questions/18180428/is-parametric-polymorphism-the-same-as-dispatching-on-arity https://stackoverflow.com/questions/18180428/is-parametric-p... for some discussion.
- deleted 13y ago[deleted]
- detrino 13y agoThis doesn't appear to have anything to do with type classes or overloading, but rather with (unconstrained) parametric polymorphism. Such a function is easy to write in C++, but the function prototype can not provide a strong guarantee that your b value will only be produced by your callback.
- sixbrx 13y ago> but the function prototype can not provide a strong guarantee It doesn't provide any such guarantee, and I think that was the whole point.
- dllthomas 13y agoThere are limits placed on you by parametric polymorphism. Adding typeclass constraints in Haskell is how you weaken those limits in a controlled way. So I think it has quite a bit to do with typeclasses. I agree "overloading" might not be the correct term to use here, although it is itself a bit... overloaded.
- sixbrx 13y agoI wouldn't say "more powerful", maybe "less constrained" (and not that that's a good thing). One thing C++ templates can't express e.g. is polymorphic recursion. http://stackoverflow.com/questions/10321856/does-c11-support-types-recursion-in-templates http://stackoverflow.com/questions/10321856/does-c11-support...
- sixbrx 13y agoWrong link, that's a different issue (type recursion). This is a good discussion about limitations of polymorphic recursion in C++: http://lambda-the-ultimate.org/node/1319 http://lambda-the-ultimate.org/node/1319