rtulip / haystack

Haystack is a compiled, statically typed, stack-based language with opt-in variable assignment.
MIT License
25 stars 2 forks source link

Sum Types #147

Closed rtulip closed 1 year ago

rtulip commented 1 year ago

Once Unit Types are supported I'd love to be able to define unit types. I'd probably leave `enum's as they are, so that syntax doesn't need to change, but add something like this:

enum struct Container {
    [] : label
    u64: value
    Str: string
}

Sum Types need some sort of way to construct them. This could be with the cast keyword like structs, but that is tricky with pure labels. Maybe something like this

Container::label as [label]
12345 Container::value as [value]
"Sum Types!" Container::string as [string]

Sum types also need a way to safely be de-structured. Maybe something like this:

fn foo(Container) {
    switch {
        case Container::label  { 
            "Found a label" println
        }
        case Container::value as [value] { 
            "Found a value: " print value println
        }
        case Container::string { println }
    }
}

fn bar(Container: c) {
    c switch {
        case Container::string as [string] { ... }
        else { ... }
    }
}

Semantically, the switch keyword, would accept any sum type, and branch to the correct case statement. The appropriate inner value will be pushed on top of the stack once the sum type is de-structured. The de-structured value can optionally be bound to a variable as part of the case statement. Unit types obviously don't push anything to the stack and the entire sum type gets dropped on a default else case.

Exhaustiveness checking would be required for this feature to be considered complete.

If possible, it would be great to have a way to handle multiple cases with a single branch, but that can be done later.

rtulip commented 1 year ago

slight change in syntax for the switch expression:

enum Struct Foo { ... }
fn takes_foo(Foo) {
    match {
        Foo::Bar as [bar] { ... }
        Foo::Baz as [baz] { ... }
    }
}
rtulip commented 1 year ago

closed with #177