I’ve been thinking about polymorphism and the lengths we’ll go to get it.
At the end of the day, we want to use the same word or symbol to call
many different functions. If equality checking (==) was
different for every type, devs would lose their minds. If we demanded
that all functions be fully qualified (i.e. namespaced) we can avoid
this problem in the most annoying way possible – nobody wants to call
Float.eq(a, b) or Integer.add(x, y). Things
get even hairier with generics; which fully qualified function do you
even use? Haskell uses typeclasses so if you want to be able to use less
than (LT) or greater than (GT) you have to
annotate that those types are orderable, e.g.
max :: Ord a => a -> a -> a
max x y = if x < y then y else x
However, I’ve been led to believe that Haskell’s typeclass implementation is fantastically complex. Let’s pretend the cost outweighs the benefit. I’ve been mulling over the idea in Roc (that I copied in Anna) that in its most extreme form might look like calling any function you want on any data without special annotations. This includes all infix operators too. At every call-site, the questions you have to answer are, which function implementation is used and does it typecheck?
If the function has been imported into the namespace (and there are no collisions), then that’s the implementation and you can typecheck normally. Otherwise, look at the module that defines the type of the first argument. If it has a function with the correct name and arity, use that implementation for codegen and typechecking. All other cases fail to compile.
I feel like this is a very elegant solution to a problem people have spent hundred of thousands of hours (collectively) solving. The one weirdness (and I personally don’t think this is a dealbreaker) crops up when considering generics.
Consider:
function max(x: a, y: b) {
if a < b then b else a
}
Does it typecheck?
I think the answer is we won’t know until max is invoked
concretely. Now that might be dissatisfying but it won’t really get us
into trouble. If we actually use it somewhere it will be typechecked and
fail or succeed. I can imagine library authors being annoying but it
remains to be seen how annoying in practice this limitation is and
conceptually I like the simplicity of it.
But idk. Maybe I’m missing an obvious flaw. 🤔