Skip to content

Instantly share code, notes, and snippets.

@GoNZooo
Last active April 27, 2023 07:41
Show Gist options
  • Save GoNZooo/bb8b076191624346eacea3deaa876e46 to your computer and use it in GitHub Desktop.
Save GoNZooo/bb8b076191624346eacea3deaa876e46 to your computer and use it in GitHub Desktop.
Nothing :: struct {}
Just :: struct($T: typeid) {
value: T,
}
Maybe :: union($T: typeid) {
Nothing,
Just(T),
}
unwrapMaybe :: proc(maybe: Maybe($T)) -> T {
value, ok := maybe.(Just(T))
if ok {
return value.value
} else {
panic("Tried to unwrap Nothing")
}
}
unwrapMaybeSwitch :: proc(maybe: Maybe($T)) -> T {
switch m in maybe {
case Nothing:
panic("Tried to unwrap Nothing")
case Just(T):
return m.value
}
unreachable()
}
safeUnwrap :: proc(maybe: Maybe($T), default: T) -> T {
return (maybe.(Just(T)) or_else Just(T){value = default}).value
}
main :: proc() {
maybeValue: Maybe(int) = Just(int){value = 42}
nothingValue: Maybe(int) = Nothing{}
value := unwrapMaybe(maybeValue)
valueFromSwitch := unwrapMaybeSwitch(maybeValue)
safeValue := safeUnwrap(maybeValue, 0)
safeValue2 := safeUnwrap(nothingValue, 0)
fmt.println(
"maybe:", maybeValue,
"value:", value,
"valueFromSwitch:", valueFromSwitch,
"safeValue:", safeValue,
"safeValue2:", safeValue2,
)
}
/*
sandbox on  main [!]
❯ odin run main
maybe: Just(T){value = 42} value: 42 valueFromSwitch: 42 safeValue: 42 safeValue2: 0
*/
Unknown :: struct {
value: string,
}
LeftParenthesis :: struct {
value: string,
}
RightParenthesis :: struct {
value: string,
}
LeftCurlyBrace :: struct {
value: string,
}
RightCurlyBrace :: struct {
value: string,
}
LeftSquareBracket :: struct {
value: string,
}
RightSquareBracket :: struct {
value: string,
}
Comma :: struct {
value: string,
}
Colon :: struct {
value: string,
}
Hash :: struct {
value: string,
}
String :: struct {
value: string,
}
Integer :: struct {
value: i64,
}
Float :: struct {
value: f64,
}
TokenType :: union #no_nil {
Unknown,
LeftParenthesis,
RightParenthesis,
LeftCurlyBrace,
RightCurlyBrace,
LeftSquareBracket,
RightSquareBracket,
Comma,
Colon,
Hash,
String,
Integer,
Float,
}
Position :: struct {
line: u32,
column: u32,
}
Token :: struct {
position: Position,
type: TokenType,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment