logoalt Hacker News

somatlast Monday at 4:21 AM2 repliesview on HN

I am not much of a programmer so I was trying to figure out what generics are. And I am sure they are great, but my inner gremlin goes in sarcastic tone "we want these elaborate type systems, but we also want typeless because that is far more convenient to use, so we invented generics, a method to untype your type system"

But really while I was reading up on what generics are I went, isn't that just python, strongly typed but your functions don't have built in type checks.


Replies

tibbarlast Monday at 4:49 AM

As you say, generics really only apply to typed languages, and they help solve very legitimate annoyance in most of those languages -- you often have some library helper or algorithm that can apply to a wide range of things, but those things differ in some way that's irrelevant to the algorithm.

For example, a mergesort algorithm works on any kind of array, as long as you can compare the elements in the array to each other. There's no point in re-implementing the algorithm for each kind of array. Yet, without generics, you'd need to do just that. At the same time, the generated code for sorting each different kind of array might need to be a little different - comparing strings and floats isn't the same assembly, for instance. So the programming language and compiler work together: you specify the algorithm once in a certain way, and the compiler can generate the right version of algorithm for each way that you need to use it.

There are many, many good reasons why you might want to work in a typed language, even though specifying the types is a bit of extra book-keeping; generics are one way to keep the pointless work down. Of course, if you can get away with a python script, there's no need to bother with all this typing business just yet, either.

masklinnlast Monday at 6:32 AM

> "we want these elaborate type systems, but we also want typeless because that is far more convenient to use, so we invented generics, a method to untype your type system"

It's rather the exact opposite. Parametric types are a way to properly type "deeply" instead of just the topmost layer. Just like inference, type parameters don't remove types.

> isn't that just python, strongly typed but your functions don't have built in type checks.

That doesn't really make any sense? Static types mean you don't have runtime type checks, since the types are known statically.

show 1 reply