Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A generic number type: num #3

Open
crawshaw opened this Issue Jan 3, 2017 · 0 comments

Comments

Projects
None yet
1 participant
@crawshaw
Copy link
Member

commented Jan 3, 2017

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 crawshaw changed the title A generic number type: `num` A generic number type: num Jan 3, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.