carbon-lang icon indicating copy to clipboard operation
carbon-lang copied to clipboard

Inferring parameter types with `auto`

Open jarble opened this issue 2 years ago • 3 comments

In C++, it is possible to infer parameter types and return types of functions using the auto keyword:

auto square(auto x){
   return x*x;
}

I tried to use this keyword in Carbon, but this program didn't compile successfully:

package sample api;

fn Square(x: auto) -> auto {
  return x * x;
}

fn Main() -> i32 {
  return Square(12);
}

Will this feature be supported in Carbon?

jarble avatar Aug 07 '22 16:08 jarble

The plans for type inference are defined here: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/type_inference.md https://github.com/carbon-language/carbon-lang/tree/trunk/docs/design#auto https://github.com/carbon-language/carbon-lang/tree/trunk/docs/design#auto-return-type

~~which says its currently limited in scope to variable declarations and function return types so function parameters seem to be out of scope.~~

The current design covers variable declarations and function return types. Type inference for function parameters is not fully designed or decided upon yet.

the following variations work with the current explorer

package sample api;

fn Square(x: i32) -> auto {
  return x * x;
}

fn Main() -> i32 {
  return Square(12);
}
package sample api;

fn Square(x: i32) -> i32 {
  var i: auto = x * x;
  return i;
}

fn Main() -> i32 {
  return Square(12);
}
package sample api;

fn Square(x: i32) -> auto {
  var i: auto = x * x;
  return i;
}

fn Main() -> i32 {
  return Square(12);
}

matthew-russo avatar Aug 07 '22 18:08 matthew-russo

function parameters seem to be out of scope

Not quite.

For variables and return types there is typically a specific expression to infer the type from, and so we call this type inference.

For parameters, the more useful thing is to make the function generic (or even templated) over the type so that it can be used with different types.

So there has been some informal discussion of having:

fn F(x: auto) { ... }

Be essentially sugar for:

fn F(x: (template _:! Type)) { ... }

Or if we disallow nested bindings in patterns (something I think we're leaning towards), then for some made up name __T:

fn F[template __T:! Type](x: __T) { ... }

I'm not sure this has been fully fleshed out and added to the design at this stage though, much less fully implemented in the explorer.

chandlerc avatar Aug 08 '22 01:08 chandlerc

We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please comment or remove the inactive label. The long term label can also be added for issues which are expected to take time. This issue is labeled inactive because the last activity was over 90 days ago.

github-actions[bot] avatar Nov 07 '22 02:11 github-actions[bot]