@@ -28,12 +28,15 @@ they're helpful, like performance sensitive branching on heterogeneous types, an
2828The simplest version of a sum type is just a list of constant variants (i.e. basically a
2929[ julia enum] ( https://docs.julialang.org/en/v1/base/base/#Base.Enums.@enum ) ):
3030``` julia
31- julia> @sum_type Fruit begin
32- apple
33- banana
34- orange
35- end
31+ using SumTypes
3632
33+ @sum_type Fruit begin
34+ apple
35+ banana
36+ orange
37+ end
38+ ```
39+ ``` julia
3740julia> apple
3841apple:: Fruit
3942
@@ -51,12 +54,10 @@ But this isn't particularly interesting. More interesting are sum types which ca
5154Let's explore a very fundamental sum type (fundamental in the sense that all other sum types may be derived from it):
5255
5356``` julia
54- julia> using SumTypes
55-
56- julia> @sum_type Either{A, B} begin
57- Left {A} (:: A )
58- Right {B} (:: B )
59- end
57+ @sum_type Either{A, B} begin
58+ Left {A} (:: A )
59+ Right {B} (:: B )
60+ end
6061```
6162This says that we have a sum type ` Either{A, B} ` , and it can hold a value that is either of type ` A ` or of type ` B ` . ` Either ` has two
6263'constructors' which we have called ` Left{A} ` and ` Right{B} ` . These exist essentially as a way to have instances of ` Either ` carry
@@ -74,19 +75,20 @@ Notice that because both `Left{A}` and `Right{B}` each carry one fewer type para
7475` Left(1) ` is * not enough* to fully specify the type of the full ` Either ` , so the unspecified field is ` SumTypes.Uninit ` by default.
7576
7677In cases like this, you can rely on * implicit conversion* to get the fully initialized type. E.g.
77- ``` julia
78+ ``` julia
7879julia> let x:: Either{Int, Float64} = Left (1 )
7980 x
8081 end
8182Left (1 ):: Either{Int64, Float64}
8283```
8384Typically, you'll do this by enforcing a return type on a function:
8485``` julia
85- julia> function foo () :: Either{Int, Float64}
86- # Randomly return either a Left(1) or a Right(2.0)
87- rand (Bool) ? Left (1 ) : Right (2.0 )
88- end ;
89-
86+ function foo () :: Either{Int, Float64}
87+ # Randomly return either a Left(1) or a Right(2.0)
88+ rand (Bool) ? Left (1 ) : Right (2.0 )
89+ end ;
90+ ```
91+ ``` julia
9092julia> foo ()
9193Left (1 ):: Either{Int64, Float64}
9294
0 commit comments