qdk icon indicating copy to clipboard operation
qdk copied to clipboard

Sum types

Open bamarsha opened this issue 2 years ago • 1 comments

Q# needs sum types (tagged unions, discriminated unions, Rust-style enums, etc.). See microsoft/qsharp-language#51, microsoft/qsharp-compiler#406.

bamarsha avatar Jul 20 '23 17:07 bamarsha

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/ and w/=)
  • 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 newtype to something like type, as the behavior of newtype doesn'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.

sezna avatar Aug 23 '23 16:08 sezna