4 ms·
It would be nice if languages allowed us to overload function names with the exact same parameters but different return types. The compiler or runtime environme
by nradov 10y ago
It would be nice if languages allowed us to overload function names with the exact same parameters but different return types. The compiler or runtime environment should be able to select the correct implementation automatically based on type inference, or allow the programmer to specify which one should be used with an annotation. This would make some code a little cleaner instead of having to give all of those functions different names.
- masklinn 10y ago> It would be nice if languages allowed us to overload function names with the exact same parameters but different return types. Haskell's typeclasses kind-of do that. `read` has type `Read a => String -> a`, so the result's type `a` (which can be inferred) drives which "Read" instance will be used: Prelude> read "1" :: Int 1 Prelude> read "1" :: Float 1.0
- dllthomas 10y ago> Haskell's typeclasses kind-of do that. You're over-hedging. As your example shows, Haskell's typeclasses exactly do that.
- masklinn 10y agoI'm mostly hedging on the "overloading" part as Haskell doesn't support arbitrary ad-hoc polymorphism in the sense of C++/Java/C# (IIRC the foundational paper on typeclasses is about making ad-hoc polymorphism less ad-hoc). Depending how far into the overloading field nradov is, typeclasses may not match their definition of or requirements for overloading. It's probably more noticeable in Rust than in Haskell.
- dllthomas 10y agoAh, that makes sense. I don't think there's a reasonable way to define "overloading" that excludes typeclasses, but it's true that there are things that can properly be termed "overloading" which typeclasses can't (or shouldn't) do.
- fredmorcos 10y ago> or allow the programmer to specify which one should be used with an annotation. That's exactly: > give all of those functions different names.
- nradov 10y agoSimilar, but not exactly the same. It would make the syntax and documentation a little cleaner.
- chriswarbo 10y agoEffectively; although "name" usually implies an opaque symbol, e.g. the language would see no difference between, say, "addAsInts" vs. "addAsFloats", compared to "addAsInts" vs. "divide". Classes, namespaces, modules, etc. allow names to have a more fine-grained structure, e.g. "int.add" and "int.divide" come from the same module, whilst "int.add" and "float.add" are alternative implementations of the same signature.
- fredmorcos 10y ago> whilst "int.add" and "float.add" are alternative implementations of the same signature. Maybe in a functional programming language like Haskell. But not in C++.
- chriswarbo 10y agoThe syntax was just an example ;) What I described is actually closer to ML.
- fredmorcos 10y agoHas nothing to do with syntax.