proposal-built-in-modules
proposal-built-in-modules copied to clipboard
Behavior of custom types in generic functions (map, len, ...)
I was very excited to see map
and len
listed as examples for generic functions that have been reinvented in a trillion hand-rolled utility modules over the years. I think that are many other generic functions that could benefit from a standard implementation, such as is-equal-by-value, shallow-copy, hash-code or is-empty ("blank").
When we build a library for generic functions, we should allow for user-defined objects to define their behavior in a call like len()
. Otherwise len()
would just be a long case
statement with pre-defined behavior for built-in types.
An existing approach for this is to define well-known symbols for specific methods that can be overriden by user-defined objects. These methods would be on the Object
prototype in other languages, but probably won't be in ES because of compatibility concerns.
New well-known symbols for length, copying, equality, etc. could be exported alongside with the functions that use them. This would also make them versionable.
What about https://github.com/michaelficarra/proposal-first-class-protocols?
I love @michaelficarra's protocol proposal, thanks for the link.
I guess the point I'm trying to make is that if bake implicit protocols in functions like map
, we should allow new types to play.
A low-tech way to do that with the existing language is to export a Symbol. If the protocol proposal gets passed and implemented (which I hope!) we can export Protocol objects instead.