motoko icon indicating copy to clipboard operation
motoko copied to clipboard

enhancement: argument type inference for invariant type parameters

Open crusso opened this issue 9 months ago • 0 comments

Motoko will complain if an invariant type parameter has under-constrained bounds, since there is no principal choice to make for the instantiation.

However, if the type parameter in question only has trivial sub and super-types (None and Any), we could probably default to the inferred type.

For example, using imperative maps:

let map = Map.fromIter([(0, "0").values(), Nat.compare)

Won't type-check, because the V(alue) type parameter is under-constrainted (None <: Text <: Any) and invariant.

So you need to add an instantiation to fromIter (or a type constraint to map).

let map = Map.fromIter<Nat, Text>([(0, "0").values(), Nat.compare)

It would probably make sense to re-solve any such type parameter to V when glb(None, V) = lub(None, V) = V (which is true for most primitive types apart from Nat and Int and any mutable array type (coz invariant) but not null, option, variants, records or immutable arrays)

let map = Map.fromIter([(0, "0").values(), Nat.compare)

would work sans type instantiation, but:

let map = Map.fromIter([(0, null).values(), Nat.compare)

Would require an instantiation, because null: Null has proper supertypes (Null <: ? T, every T).

crusso avatar Apr 11 '25 15:04 crusso