Function specialization #666
KtorZ
started this conversation in
Core language features
Replies: 1 comment
-
Interesting |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
What is your idea? Provide a use case.
Provide a way to write specialized implementation of generic functions, by forcing the type of one (or more) parameters to a concrete representation, then, let the compiler figure out what definition to use at call-site.
For example, take the
dict.get
function in the standard library:we could imagine the ability to provide a specialized version of that function for
key = ByteArray
, like so:Internally, that would be a new type of definition, that would go side-by-side with functions. When calling a function, we could - at compile time - check if one specialization matches and use that definition instead. This also allows using different arguments even (for example, to remove a function no longer needed because the type is known).
Why is it a good idea?
Taking the example of
dict.get
: the only possible implementation from that is to traverse the inner list until we find a matching key. If the key isn't in the dictionary then we need to traverse the entire list. However, because items in the dictionary are ordered by ascending list, you could in principle stop searching when meeting a key that is higher than the searched one.This means that, we can not only provide a simpler interface for some special known cases, but also provide more efficient implementations. That's particularly useful for building performant libraries with not so much overhead.
What is the current alternative and why is it not good enough?
Alternatives to that are mainly:
Use already specialized function all-the-way; which looses the generic aspect of function and thus, the re-usability and elegance that comes with it. It's more work to maintain multiple implementations as well should we need different specialization.
Pass extra argument to the function when possible to customize the behavior, e.g.
Which is unsatisfactory because it makes the overall module API less orthogonal / composable (and thus, harder to use and navigate). It's also harming the user experience by adding extra parameters that may not be relevant for some instances of
key
; only because certain cases can be optimized.Beta Was this translation helpful? Give feedback.
All reactions