Skip to content

Instantly share code, notes, and snippets.

@thecaralice
Created February 16, 2023 07:52
Show Gist options
  • Save thecaralice/c0bd03d15b5c6ad7f71479543d9e42ac to your computer and use it in GitHub Desktop.
Save thecaralice/c0bd03d15b5c6ad7f71479543d9e42ac to your computer and use it in GitHub Desktop.
from dataclasses import dataclass
from typing import TypeVar, Generic, cast
T = TypeVar("T")
@dataclass
class Some(Generic[T]):
value: T
Option = Some[T] | None
class NoneError(ValueError): pass
# how do i define this as `Option.unwrap`?
def unwrap(opt: Option[T]) -> T:
match opt:
case Some(val):
return val
case None:
raise NoneError("called `Option.unwrap()` on a `None` value")
# The adult has seen it all, and can handle any drink well.
# All drinks are handled explicitly using `match`.
def give_adult(drink: Option[str]) -> None:
match drink:
case Some("lemonade"):
print("Yuck! Too sugary.")
case Some(inner):
print(f"{inner}? How nice.")
case None:
print("No drink? Oh well.")
# Others will `panic` before drinking sugary drinks.
# All drinks are handled implicitly using `unwrap`.
def drink(drink: Option[str]):
# `unwrap` returns a `NoneError` when it receives a `None`
inside = unwrap(drink)
if inside == "lemonade":
raise ValueError("AAAaaaaa!!!!")
print(f"I love {inside}s!!!!!")
def main():
water = Some("water")
lemonade = Some("lemonade")
void = None
give_adult(water)
give_adult(lemonade)
give_adult(void)
coffee = Some("coffee")
nothing = None
drink(coffee)
drink(nothing)
if __name__ == "__main__":
main()
// The adult has seen it all, and can handle any drink well.
// All drinks are handled explicitly using `match`.
fn give_adult(drink: Option<&str>) {
// Specify a course of action for each case.
match drink {
Some("lemonade") => println!("Yuck! Too sugary."),
Some(inner) => println!("{}? How nice.", inner),
None => println!("No drink? Oh well."),
}
}
// Others will `panic` before drinking sugary drinks.
// All drinks are handled implicitly using `unwrap`.
fn drink(drink: Option<&str>) {
// `unwrap` returns a `panic` when it receives a `None`.
let inside = drink.unwrap();
if inside == "lemonade" { panic!("AAAaaaaa!!!!"); }
println!("I love {}s!!!!!", inside);
}
fn main() {
let water = Some("water");
let lemonade = Some("lemonade");
let void = None;
give_adult(water);
give_adult(lemonade);
give_adult(void);
let coffee = Some("coffee");
let nothing = None;
drink(coffee);
drink(nothing);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment