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

Type Switch Operator #113

Open
DavePearce opened this issue Aug 10, 2022 · 1 comment
Open

Type Switch Operator #113

DavePearce opened this issue Aug 10, 2022 · 1 comment

Comments

@DavePearce
Copy link
Member

DavePearce commented Aug 10, 2022

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

  • The ? operator is inextricably linked with std::error::Error and is used for error propagation.
  • For Whiley, a more general version of it is desirable.

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
Copy link
Member Author

DavePearce commented Aug 10, 2022

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) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant