Skip to content

Instantly share code, notes, and snippets.

@haller33
Last active December 6, 2023 12:32
Show Gist options
  • Save haller33/2c68987accf314167842b8d975331572 to your computer and use it in GitHub Desktop.
Save haller33/2c68987accf314167842b8d975331572 to your computer and use it in GitHub Desktop.
Safe Divísion with Either "monad" on Odin programming language
package main
import "core:fmt"
// te error handling is just this two, struct and union
Left_Err :: struct {
nok: bool,
data: any,
msg: string,
file_name: string,
line: int,
procedure_name: string,
}
Either :: union($Right: typeid) #no_nil {
Right,
Left_Err,
}
dive :: proc(num: int, base: int) -> Either(int) {
if base == 0 do return Left_Err{nok = true, msg = "some division problem", data = base,
line = #line, procedure_name = #procedure, file_name = #file}
return num / base
}
// this is helper functions
not_left :: proc(typed: Either(int)) -> bool {
#partial switch i in typed {
case Left_Err:
return false
case:
return true
}
}
main :: proc() {
data_one := dive(1, 1)
if (not_left(data_one)) {
fmt.println("corret")
fmt.println(data_one)
} else {
fmt.println("Error")
fmt.println(data_one)
}
data_two := dive(1, 0) // safe division
if (not_left(data_two)) {
fmt.println(data_two)
} else {
fmt.println("Error")
fmt.println(data_two)
}
return
}
@haller33
Copy link
Author

version of Odin

odin version
odin version dev-2022-12:521ed286

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment