ng icon indicating copy to clipboard operation
ng copied to clipboard

A generic number type: num

Open crawshaw opened this issue 9 years ago • 0 comments

Whether or not neugram adopts a full parametric type system, they come with a readability cost. Intermediate generalized types are given names like T, or U. A programmer reading code has to track possible meanings of these meaningless names, which is unfortunate.

This proposal is about introducing a single implicit type parameter: num. The type can only hold the value of one of the builtin machine words.

Context implicitly defines num. A function or type written over num is parameterized, and can be used for any value of num.

Functions and types can be parameterized over a single type parameter. The type parameter can only resolve to numeric scalar types and must have the name num. Its appearence anywhere in the type declaration means the function is generic:

min := func(x, y num) num {
	if x < y {
		return x
	}
	return y
}
print(min(float64(4.5), float64(4.1))) // prints 4.1
print(min(integer(4), integer(3)))     // prints 3
print(min(integer(4), float64(3.2)))   // compile error

When declaring a variable using type inference from a constant, the variable adopts the type of num.

add2 := func(x num) num {
	two := 2
	return x + two
}
add2(float32(4.5)) // two was a float32
add2(int64(4))     // two was an int64

In a scope where num has not been defined (including the top-level), num takes on the default parameterization of float64.

> x := num(4.3) // x is a float64

(The first comment of this issue is kept up-to-date with the current proposal. When commenting on it, quote any relevant sections and respond to the quote.)

crawshaw avatar Jan 03 '17 07:01 crawshaw