thautwarm/MLStyle.jl

Sum type

Opened this issue · 1 comments

Currently I think MLStyle makes unions but not sum types. Do you think MLStyle could make this kind of type structure? The union cannot be extended from outside, which may be appropriate sometimes.

# Credit to @MasonProtter for this code.
using MLStyle

no_constructor() = nothing

macro new(T, args...)
    esc(Expr(:new, T, args...))
end

struct Chocolate
    no_constructor()
end
struct Vanilla
    no_constructor()
end
struct Strawberry
    no_constructor()
end

struct Flavour
    x::Union{Chocolate, Vanilla, Strawberry}
end
Chocolate() = Flavour(@new Chocolate)
Vanilla() = Flavour(@new Vanilla)
Strawberry() = Flavour(@new Strawberry)

MLStyle.@as_record Flavour

cc @MasonProtter

The issue can be very general to discuss about. I'd recommend you the Scala's approach to sum types, and I think in this approach, we can treat a concrete type in Julia as a constructor of some sum type.