VL-Language icon indicating copy to clipboard operation
VL-Language copied to clipboard

[Proposal] Sum Types / Tagged Union

Open gregsn opened this issue 4 years ago • 2 comments

Many functional languages come with a neat data type idea often called sum types.

https://en.wikipedia.org/wiki/Tagged_union

type Tree =
  | Leaf
  | Node of value: int * left: Tree * right: Tree

This sounds like a bit like an enum #12 on steroids: For each possible entry, you already have the possibility to attach some more data that makes sense for this entry only.

But not only that. You could also think of it as a built-in data type for implementing the state pattern #10 in a less verbose way. We'd be able to address #8 without the need to tell everybody about an abstract private data type and a bunch of private implementations of it.

We could maybe offer a data type (in that drop-down) called Variant (or whatever).

And below that add a new section to add entries to that Variant.

You would now be able to

  • Choose one Entry
  • See the patch for that entry
  • Add new fields and behavior
  • Add new operations for the whole thing
  • Add new operations for just one entry (...)

The system compiles to the state pattern (#10)

  • an interface
  • classes implementing the interface

the interface additionally would surface

  • an enum property
  • type switch regions that hand you the different system states, so that you can easily match and react from outside

TBD in detail...

The main question here: Would that long term wish influence how we address #12? Or should this proposal be seen as an enhancement to an enum definition, somehow suggesting we should discuss this before defining how an enum definition should look like?

gregsn avatar Jun 22 '20 20:06 gregsn

👍 for Sum types

Ideally VL would have them compatible with the rest of the .Net ecosystem, however I don't know how realistic it is to target F# compatibility.

C# might get them - but not before C# 10 at least (so you have to wait or be incompatible..) and it's not likely to be directly compatible with F#

beyon avatar Jun 23 '20 16:06 beyon

nice! missed that one. while it definitely makes sense to align with roslyn/.net implementation. probably worth peeking at rust-lang which implemented it deeply into its core.

without having read through the whole c# thread about it, i wonder how well a tagged union would integrate into the 'classic' enum and flags which heavily borrow functionality from their underlying (fixed size) value type, casting, numeric comparison, bit ops,...

woeishi avatar Sep 01 '20 00:09 woeishi