tl icon indicating copy to clipboard operation
tl copied to clipboard

how to detect that unions are acceptable for polymorphic functions?

Open hishamhm opened this issue 4 years ago • 0 comments

Consider this example, adapted from #317:

local record Library
   func: function(string): {number}
   func: function(number): {number}
end

local library: Library

local function f(x: string | number): {number}
   return library.func(x) -- fails with got string | number, expected string
end

open in playground

It's reasonable to see x as a valid value for library.func there.

Is there an algorithm to "flatten" these poly types into functions with unions and still retain identical semantics? given the internal poly type's ordering/arity semantics + complex nested types, this seems difficult: but perhaps some heuristics could be doable for easy cases.

Reminder that we can't do the naive thing and "just join poly arguments into unions" or "destructure unions when matching arguments", as there are cases in which it won't be possible:

local record Library
   func: function(string, number): {number}
   func: function(number, boolean): {number}
end

Here, func can't be simplified to function(string | number, number | boolean): {number}, because (string, boolean) is not a valid argument combination.

hishamhm avatar Jan 04 '21 22:01 hishamhm