Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Option.take() for swapping with None #809

Merged
merged 3 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion guppylang/std/option.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
OptionTestCompiler,
OptionUnwrapCompiler,
)
from guppylang.std.builtins import owned
from guppylang.std.builtins import mem_swap, owned
from guppylang.tys.arg import Argument, TypeArg
from guppylang.tys.param import TypeParam

Expand Down Expand Up @@ -51,6 +51,14 @@ def unwrap(self: "Option[T]" @ owned) -> T:
Panics if the option is a `nothing` value.
"""

@guppy
@no_type_check
def take(self: "Option[T]") -> "Option[T]":
"""Swaps the value of `self` with `nothing` and returns the original value."""
n: Option[T] = nothing() # type: ignore[type-arg, valid-type]
mem_swap(n, self)
return n


@guppy.custom(OptionConstructor(0))
@no_type_check
Expand Down
19 changes: 19 additions & 0 deletions tests/integration/test_option.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import no_type_check
from guppylang.decorator import guppy
from guppylang.module import GuppyModule
from guppylang.std.option import Option, nothing, some
Expand All @@ -8,6 +9,7 @@ def test_none(validate, run_int_fn):
module.load(Option, nothing)

@guppy(module)
@no_type_check
def main() -> int:
x: Option[int] = nothing()
is_none = 10 if x.is_nothing() else 0
Expand All @@ -24,6 +26,7 @@ def test_some_unwrap(validate, run_int_fn):
module.load(Option, some)

@guppy(module)
@no_type_check
def main() -> int:
x: Option[int] = some(42)
is_none = 1 if x.is_nothing() else 0
Expand All @@ -34,3 +37,19 @@ def main() -> int:
validate(compiled)
run_int_fn(compiled, expected=42)


def test_take(validate, run_int_fn):
module = GuppyModule("test_range")
module.load(Option, some)

@guppy(module)
@no_type_check
def main() -> int:
x: Option[int] = some(42)
y = x.take().unwrap()
is_none = 1 if x.is_nothing() else 0
return y + is_none

compiled = module.compile()
validate(compiled)
run_int_fn(compiled, expected=43)
Loading