Whiley / RFCs

Request for Comment (RFC) proposals for substantial changes to the Whiley language.
3 stars 2 forks source link

Type Switch Operator #113

Open DavePearce opened 2 years ago

DavePearce commented 2 years ago

The type switch operator is inspired by the ? operator in Rust. Some points:

In particular, since we have union types in Whiley, the ? operator should work with them. For example:

function test() -> (int|bool r):
   int x = other()?
   return x + 1

function other() -> (int|bool r):
   1

What's happening here is that, by exploiting forward type information from x the ? operator attempts to resolve by pulling out the desired item, otherwise return what is left from the enclosing function. For that to type check, what's left must fit into the return type.

This then allows us to encode exceptional control flow roughly as is done in Rust.

DavePearce commented 2 years ago

The ? operator is actually a bit more general than I gave it credit for above. For example, the following is fine:

pub fn test() -> Option<u32> {
   let x = other()?;
   Some(x + 1)
}

pub fn other() -> Option<u32> { Some(1) }

However, the following does not work and the compiler complains that ? needs either an Option or a Result.

enum Union<X,Y> { Left(X), Right(Y) }

pub fn test() -> Union<u32,bool> {
   let x = other()?;
   Union::Left(x + 1)
}

pub fn other() -> Union<u32,bool> { Union::Left(1) }