qdk
qdk copied to clipboard
Sum types
Q# needs sum types (tagged unions, discriminated unions, Rust-style enums, etc.). See microsoft/qsharp-language#51, microsoft/qsharp-compiler#406.
The points brought up in https://github.com/microsoft/qsharp-language/issues/51 are very good, and the descriptions are thorough. This comment builds on that problem statement.
There are some things we want to "fix" with UDTs. They are:
- Copy-and-assign syntax and evaluate-and-reassign synax (
w/andw/=) - Disallowing a mixture of named and unnamed fields. Instead, we should enforce either all named or all unnamed fields. In other words, only support tuple records and struct records, but not a mixture of the two.
- Change the keyword
newtypeto something liketype, as the behavior ofnewtypedoesn't match the semantic expectations set up by the word. - Replace unwrap syntax (
!) with pattern matching and struct field name accesses.
The below code snippet outlines a type definition syntax that addresses parts of these concerns, but does not address pattern matching and assignment syntax:
// named fields (struct-type)
type Foo {
A: B,
}
// anonymous fields (tuple-type)
type Foo(B)
// with explicit constructors, for a discriminated union
// `A` is a struct variant
// `B` is a tuple variant
// `C` is a unit variant (subset of tuple variant with syntactic sugar to omit the `()`)
type Foo = A { field: Integer },
| B (Int, Double)
| C
This syntax provides for both defined and implicit constructor definitions, and a similar syntax for both tuple and struct types.