Skip to content

Commit

Permalink
Implement is_sumtype (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tortar authored Jul 6, 2024
1 parent 77cf02c commit 88cc7c9
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
5 changes: 3 additions & 2 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

```@docs
@sumtype
DynamicSumTypes.variant
DynamicSumTypes.allvariants
variant
allvariants
is_sumtype
```
15 changes: 12 additions & 3 deletions src/DynamicSumTypes.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

module DynamicSumTypes

export @sumtype
export @sumtype, variant, allvariants, is_sumtype

unwrap(sumt) = getfield(sumt, :variants)

Expand Down Expand Up @@ -42,7 +42,7 @@ macro sumtype(typedef)
variants::Union{$(variants...)}
$type(v) = $(branchs(variants, :(return new(v)))...)
end
function variant(sumt::$type)
function DynamicSumTypes.variant(sumt::$type)
v = DynamicSumTypes.unwrap(sumt)
$(branchs(variants, :(return v))...)
end
Expand All @@ -66,7 +66,8 @@ macro sumtype(typedef)
v = DynamicSumTypes.unwrap(sumt)
print(string($type), "'.", string(v))
end
allvariants(sumt::Type{$type}) = tuple($(variants...))
DynamicSumTypes.allvariants(sumt::Type{$type}) = tuple($(variants...))
DynamicSumTypes.is_sumtype(sumt::Type{$type}) = true
$type
end)
end
Expand Down Expand Up @@ -129,4 +130,12 @@ julia> allvariants(AB)
"""
function allvariants end

"""
is_sumtype(T)
Returns true if the type is a sum type otherwise
returns false.
"""
is_sumtype(T::Type) = false

end
2 changes: 2 additions & 0 deletions test/sumtype_macro_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ end
@test g1.e === g2.e === 1
@test hasproperty(g1, :e) == true
@test hasproperty(g1, :w) == false
@test is_sumtype(typeof(g1)) == true
@test is_sumtype(G) == false

f.a = (3, 3)
@test f.a == (3, 3)
Expand Down

0 comments on commit 88cc7c9

Please sign in to comment.