[swift-evolution] [Idea] Creating an enums as a sum of multiple other enums

Ahmad Alhashemi ahmad at ahmadh.com
Mon Jul 31 19:43:45 CDT 2017


I’ve been writing an interpreter in Swift and have been finding enums incredibly useful. One feature thought that I thought would make life easier is the ability to create a super-enum that contains as its cases all the cases of its constituent enums:

> enum UnaryOperator {
>     case not
> }
> 
> enum BinaryOperator {
>     case and
>     case or
> }
> 
> case BooleanLiteral {
>     case `true`
>     case `false`
> }
> 
> typealias Token = UnaryOperator | BinaryOperator | BooleanLiteral

It would then be possible to do something like this:

> scanToken() -> Token
> 
> indirect enum Expr {
>     case binary(op: BinaryOperator, lhs: Expr, rhs: Expr)
> }

For example, a number of functions in the recursive descent parser can only return a subset of all possible expressions.

Of course it’s already possible to represent the same data structure like this:

> enum Token {
>     case binaryOperator(BinaryOperator)
>     case unaryOperator(UnaryOperator)
>     case booleanLiteral(BooleanLiteral)
> }

Perhaps what I’m suggesting could just be syntactic sugar, but it’d make it much easier to switch over `Token` without worrying about all of the nested enums. The feature becomes even more useful if you think about a deeper hierarchy of enums. It would bring some of the power of protocols/POP to enums.

This raises a few questions such as:
- Case name collisions
- Associated types
- Raw values

But I can’t think of anything that cannot be addressed with sensible rules and conditions.

Interested to read your thoughts.

-Ahmad


More information about the swift-evolution mailing list