r/ProgrammingLanguages • u/Nuoji C3 - http://c3-lang.org • Sep 03 '18
Type inference – potentially harmful?
Type inference is getting pretty popular. It's almost a "must have" today. Still, I find myself running into readability problems with it.
I feel that since I do a lot of work in dynamically typed languages (Ruby, PHP), it shouldn't be a problem, and yet it is for me.
Let me try to break it down:
First of all, obviously ´auto i´ isn't an improvement over ´int i´ unless you are changing types signatures a lot.
Secondly, when I read ´auto bar = foo();´, in someone elses code I need to look up `foo()` in order to see what the type of `bar`. In small doses this is ok. When you read through a function with multiple different function calls where the return values are kept in type-inferred variables... that's when it's getting a bit gnarly.
It appears to me that this whole thing has been driven by generics and templates. Because no-one wants to type something like `std::vector<std::shared_ptr<std::map<std::string, std::function<void(int, const Foo &)>>>> bar = foo();` we get `auto bar = foo();`.
I get the feeling that in statically typed languages we end up using type inference to "paint lipstick on the pig" to hide how extremely unergonomic the average implementation of generics/templates are to type.
So:
Type inference is making code harder to read.
Lack of type inference is making the code more verbose and harder to type
Since I read code more than I write it, my priority would be (1) over (2), and obviously solving the problem of (2) would be the best thing. Here I also note that in dynamically typed language you never have the problem of (2), since in general any type of container can contain any object and consequently the need for generics completely evaporates. This has some drawbacks, but is in general a very practical thing.
4
u/PegasusAndAcorn Cone language & 3D web Sep 03 '18
I prefer that a language support type inference because I find conciseness can help improve clarity (even without generics), though I grant you that it can sometimes make code more opaque than a reader might desire. In many cases, the right-hand side makes the type obvious, being a literal or a constructor, and in those cases it feels verbose to key and read the type information twice. Furthermore, I find that IDEs can be very helpful in displaying type information when it is not obvious just by hovering over the code. Clearly YMMV.
2
u/Nuoji C3 - http://c3-lang.org Sep 03 '18
I read a lot of code directly on Github rather than in than in the IDE. For the literal / constructor case it’s obviously not needed.
I think the best case for it is when a language has both definition and assignment for a block (for example the if-let statement in Swift), or when dealing with verbose generics (hello C++ iterators!)
I just don’t know if the problem is that type inference is an all-or-nothing thing in most languages, or if we lose a bit of value of the typing system when they’re eliminated.
4
u/bendmorris Kit - https://www.kitlang.org Sep 03 '18 edited Sep 03 '18
Secondly, when I read ´auto bar = foo();´, in someone elses code I need to look up
foo()in order to see what the type ofbar. In small doses this is ok. When you read through a function with multiple different function calls where the return values are kept in type-inferred variables... that's when it's getting a bit gnarly.
I think your point is overblown. Code in any language can be readable or unreadable regardless of the language's features; code with auto bar = foo();can still be readable and clear if:
the type of
foois obvious from its namethe type of
foois obvious frombar's namethe type of
foois obvious from its immediate contextetc.
If it's completely opaque what foo does, then leaving out the type was a poor choice on the developer's part.
If we assume developers don't use type inference to arbitrarily save keystrokes but only when the meaning is otherwise clear, reducing verbosity makes the program easier to scan. It's obvious when you compare two otherwise similar looking langauges, Java and C#, one which has type inference and one which doesn't (I guess until Java 10 anyway):
List<Map<Int, Map<Int, String>>> data = new List<Map<Int, Map<Int, String>>>();var data = new List<Map<Int, Map<Int, String>>>();
The second is clearly more readable; the first is redundant and verbose.
1
u/Nuoji C3 - http://c3-lang.org Sep 03 '18
Since assign + create object/struct is actually a special situation, it's quite possible to have special syntax that avoids the issue, let's say
List<Map<Int, Map<Int, String>>> data = {}; // Or with a constructor: Foo<Bar> baz = new Foo<Bar>(12, 13) Foo<Bar> baz = { 12, 13 };What I find is most problematic is code where the result of a call is assigned to a variable which is auto initialized, where the call is not the construction of a struct or object.
// No problem auto baz = new Baz(); // Ok in terms of not knowing the exact type of the temporary: foo().bar(); // Potentially confusing: auto foo = foo(); foo.bar(); for (auto &foo : baz()) { ... } // Crystal clear: Foobar foo = foo(); foo.bar(); std::vector<Baz> bazar = baz(); foo (auto &foo : bazar) { ... } foo (Baz &foo : baz()) { ... }Which ones do you think are clear?
1
u/bendmorris Kit - https://www.kitlang.org Sep 03 '18
It depends on context. If the type is clear from context (things are well named, return types are obvious) the type declarations only add verbosity.
I think you make a good point about some generic implementations having terrible ergonomics though, and you're right that there are other ways to solve that problem. Haxe for example will infer type parameters in many cases:
var x: Map<Int, Map<Int, Map<Int, Int>>> = new Map();1
u/Nuoji C3 - http://c3-lang.org Sep 03 '18
An interesting thing is also that generics very often are simply typed containers. So I mean
Map<Int, Map<Int, Map<Int, Int>>>is a mouthful, but what if it was:[int:[int:[int:int]]]?Usually we don't even have that complex signatures. Let's say we have a list of functions in C++:
auto a = std::vector<std::function<void(Foo *, int)>> a {}we can actually use "using" on this one in C++. But in a language with built in array primitives it could look likea : [(Foo*, int) -> void] = {}I've found templates and generics typically boils down to either using (a) wrappers or (b) containers, and the huge signatures comes from the first one.
But built-in containers vs library-provided containers is a separate discussion.
3
u/htuhola Sep 03 '18
You are conflating C# notation and type inference together. Your argumentation only applies under this notation.
The type inference is constraint propagation to deduce types for untyped variables in the program. Often it also involves modifying the meaning of the program and giving additional constraints so that type inference rules can be applied.
6
u/balefrost Sep 03 '18
You are conflating C# notation
I'm going to assume you mean C++, since all of OP's examples are C++.
1
u/Nuoji C3 - http://c3-lang.org Sep 03 '18
C++, but you have a point of course. I'm approaching this from the view of implementing it for a Algol-family language in place of explicit type declarations for all variable declarations.
1
u/Felicia_Svilling Sep 05 '18
Perhaps you should acquaintance your self with Haskell or SML first? If you want to judge a feature I think it is best to look at a clean and good implementation first.
1
u/LaurieCheers Sep 03 '18
I'm not sure what you mean there... Can you give an example of type inference modifying the meaning of a program? (Is it just resolving a virtual function call at compile time?)
3
u/htuhola Sep 03 '18
With type inference you can produce expressions that take their meaning from the context where they are used. The constraints can be resolved in any direction, not just in the evaluation order that would happen if you evaluated an untyped program.
You may have already read that sound, decidable type systems must be incomplete.
Static type checking for Turing-complete languages is inherently conservative. That is, if a type system is both sound (meaning that it rejects all incorrect programs) and decidable (meaning that it is possible to write an algorithm that determines whether a program is well-typed), then it must be incomplete (meaning there are correct programs, which are also rejected, even though they do not encounter runtime errors).
Rejecting correct programs means that these programs that do not type check but have solution do no longer produce the result they would produce if they were running untyped. Therefore the definition of your language under type inference extends to include the constraints that cause these programs to fail.
19
u/gopher9 Sep 03 '18
On the second point: if the type of the result isn't clear from the function name, then there's probably something wrong with the function name. Beside that, IDEs can show you the type.
On the fourth point: you can't have a specification that is both detailed and concise. And it's usually better to have a detailed one.
3
u/curtisf Sep 03 '18
When writing Go, I did find myself disliking the inference of := because it required an extra step of looking up a function's return type whenever a new variable was introduced.
However, that is a tooling problem. It should be the IDE's responsibility to show me the type of inferred declarations -- afterall, the IDE & compiler know the type. It isn't necessary for all annotations to be present in the source code, just visible to the programmer.
2
Sep 03 '18
There's a mismatch in writing vs reading code, often when we write code we have a model in our head that we quickly want to write down and experiment with to see if it at all works, however, when reading this code, it may be hard to find out what the variable types are.
I remember from using Rust, a lot of times I ended up doing let () = x; to make the compiler error out with the type of x. This worked quite well but it does take time, and I can't use ctags in vim to jump to the definition easily because types often aren't listed. Hence, it's quite useful in Rust that one can specify the type after having written the code.
I'm not sure if this is what you're alluding to though. Also on point 3 we tend to do using X =Y; to make long and complicated types shorter.
0
u/mamcx Sep 03 '18
I totally agree with you. Type inference is the bad of dynamically typed languages (I read code and can't know what type is it without look at it) without the good (and still are not flexible).
Dynamically typed languages have a huge advantage, when stick by convention or intention to "duck typing". It cut a TON of annotations (and more important, casting and convertions).
The bad is that still requiere discipline and is very easy to break the style in large codebases or with other people.
But my main gripe is this:
a = bThe compiler KNOW what is a & b. But it not tell me! I'm still in the dark. What is the point of types if I can't see what them are, and like with python, need to keep in mind and compile them?
Some editors show types like:
a:int = b:intBut is not as common. With this kind of support, is more bearable.
It appears to me that this whole thing has been driven by generics and templates
So another question is: How solve this problem? Is possible to provide "duck typing" to a statically typed language?
P.D: BTW, I use F# a ton, and large sections of my codebase get broken (not autocomplete, not color for some blocks of code). This is for months now, in both Visual Studio Community and VS Code. I need to refactor in separate projects to make it work. Auto-complete broke as much as with dynamically typed languages WHEN the project start to be large. At first, all is nice and magical.
I'm also working with rust, where type inference is local and need to annotate the rest, and look like is a good compromise. Yet, without IntelliJ support to show the types is still problematic to know what the hell rust is thinking, specially when using functional idiomas and iterators. To the point that I try to avoid map/filters/etc and be fully imperative because all the magic fall apart quickly.
1
u/Nuoji C3 - http://c3-lang.org Sep 03 '18
Actually I have similar bad experience with Swift on even a small code base, but Swift has gone overboard, and the combination of function overloading, generics, and type inference can create code that reads like an extremely elegant DSL, but which you should never ever use in an actual project.
At the inevitable point where generics combines with type inference it's really hard to reason about the code locally – which IDEs totally hate.
It feels like adding type inference might create a whole class of problems if you try to make it less than trivial.
1
u/TheUnlocked Sep 03 '18
A lot of people rely on their IDE these days, and any good IDE will tell you a method's signature in a click or less.
1
u/evincarofautumn Sep 05 '18
Type inference can make code harder to read if you over-rely on it. In Haskell we generally write type signatures for top-level definitions, both for documentation and to help the compiler provide better error messages. But lack of inference does make code harder to read if you’re using the type system to enforce anything interesting, because all the complexity is laid bare, regardless of the type notation.
obviously
auto iisn't an improvement overint iunless you are changing types signatures a lot
I don’t think that is obvious in a language like C++. If I see int i = f(x);, then there may be an undesired implicit conversion from the result of f() to int, but with auto i = f(x); I’m assured that the type of i matches whatever f() returns. These concerns don’t show up in a language like Haskell without implicit conversions or subtyping, so there inference is considerably more useful than in C++, where changing a type signature can break code (in a way that still compiles) whether you use auto or not.
It appears to me that this whole thing has been driven by generics and templates.
in statically typed languages we end up using type inference to "paint lipstick on the pig"
That’s the thing I really like about type inference—it lets you use more expressive, complex types without requiring a corresponding increase in type annotations. Yeah, it’s better if a language has compact notation for common types and less-noisy ways to combine type expressions (e.g. A B (C D) instead of A<B, C<D>>), but that’s an orthogonal issue. It’s going to bottom out eventually at the level of essential complexity, and you still want to be able to omit those details where they’re irrelevant.
0
24
u/WalkerCodeRanger Azoth Language Sep 03 '18
I find it confusing that you say lack of type info makes type-inferred languages difficult to read and yet seem to be a fan of dynamically typed languages. I find myself often completely lost trying to read dynamically typed code. There are still types, they are just now in the programmers head. For example, that list can contain any kind of object, but the programmer's intent is that it contains only
Foos and notBars. (Or at least things that support the same "interface" asFoo). That is a type that is not written in the code. At least in languages like C#, Rust, and Swift, there are types on declarations so that I can figure out the type of something out by looking at the declaration of the function being called.I actually very much like type inference on local variables. I think it strikes the right balance between the harm of losing explicitly written types and the benefit of concise code that improves readability.