ceylon/ceylon-spec — Issue #115: Automatic promotion of expressions to functions
Author: gavinking
Created: 2011-12-21 04:28:26+00:00
State: open
Labels: request for feedback

Automatic promotion of expressions to functions

Ceylon eschews implicit type conversion because of the ambiguities it introduces in the type system. However, there is a case where a certain kind of type promotion looks safe and unambiguous to me. I'm talking about promoting `T` to `Callable` in a return statement or specifier. (Note that this is not a proposal to build this promotion into the *expression* syntax. For example, it would not happen to an argument expression.)

Consider the following examples:

function cube(Float x) = x**3;

function scaler(Float scale)(Float x) {
return scale*x;
}

In each of these cases, we encounter an assignment of an expression of type Float to something that is of type `Callable` for some `T`. It seems to me that the typechecker can unambiguously infer that what is meant is the following:

function cube(Float x) = function (Float x) x**3;

function scaler(Float scale)(Float x) {
return function (Float x) scale*x;
}

I don't see any real value in forcing people to go through the motions of writing in the `function (Float x)` bit. To me it's blindingly obvious what the intent is. And I also like the ability to write simple single-expression functions in "ML"/mathematics style. It cuts out some verbosity. To my eyes:

function cube(Float x) = x**3;

compares quite favorably with

function cube(Float x) { return x**3; }

And I think there would be a lot of resistance to having to write:

function scaler(Float scale)(Float x) {
return function (Float x) scale*x;
}

For a function that returns a function. You don't have to do that in other statically-typed languages with higher-order functions.

Potential negatives:

1. This gives you another way to write a function that is arguably unfamiliar to a person with experience mainly in C-like languages. On the other hand if this person has ever studied mathematics in their life, they will probably get the idea really quickly.

2. OK, OK, there *is* an ambiguous case here:

function x3(Float x) = x**3;
function cube(Float x) = x3;

Does "cube" have return type `Float` (no promotion) or `Callable`, (after promotion to `Callable,Float>`). I think it's pretty trivial to resolve this ambiguity by either:

1. simply never promoting expressions of type `Callable`, or
2. requiring an explicit return type declaration for promotion to happen.

I would be perfectly happy with option 1.