Code-gen improvements - discriminated unions #888
louthy
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This release features updates to the
[Union]
feature of language-ext (discriminated union generator) as well as support for iOS Xamarin runtime code-genMatch
function for each unionMap
function for each union.ToString
andGetHashCode
- allowing for your own bespoke implementationsRecord<A>
,Range
, and other types) now falls back to building implementations withExpression
.Match
Unions can already be pattern-matched using the C#
switch
statement andswitch
expression. Now you can use the generatedMatch
function like other built-in types (such asOption
,Either
, etc.). This match function enforces completeness checking, which the C#switch
can't do.There are two strategies to generating the
Match
function:[Union]
type is aninterface
, then the generatedMatch
function will be an extension-method. This requires your union-type to be a top-level declaration (i.e. not nested within another class). This may be a breaking change for you.[Union]
type is anabstract partial class
, then the generatedMatch
function will be an instance-method. This doesn't have the limitation of theinterface
approach.And so, if you still need unions nested within other classes, switch the interface to an abstract class:
This is an example of an interface based union:
This is the equivalent as an abstract class:
Map
One thing that is true of all algebraic-data-types (of which category discriminated-unions fall into); is that there is exactly one way to generate a functor
Map
function (Select
in LINQ) it's known as a theorem for free. And so the implementation forMap
andSelect
are now provided by default by the code-gen.So, for the example below:
This code is auto-generated:
This will currently only support single generic argument unions, it will be expanded later to provide a
Map
function for each generic argument. The other limitation is that if any of the cases have their own generic arguments, then theMap
function won't be generated. I expect this to cover a large number of use-cases though.Any problems please report in the repo Issues.
Paul
This discussion was created from the release Code-gen improvements - discriminated unions.
Beta Was this translation helpful? Give feedback.
All reactions