Last active
December 6, 2023 12:32
-
-
Save haller33/2c68987accf314167842b8d975331572 to your computer and use it in GitHub Desktop.
Safe Divísion with Either "monad" on Odin programming language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
version of Odin