Skip to content

Commit

Permalink
Add filter method to Maybe
Browse files Browse the repository at this point in the history
  • Loading branch information
HKGx committed Nov 22, 2022
1 parent 019915d commit a3dda3a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
22 changes: 22 additions & 0 deletions perhaps/maybe.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,22 @@ def unwrap_or_else(self, f: Callable[[], T]) -> T:
"""
...

@abstractmethod
def filter(self, f: Callable[[T], bool]) -> "Maybe[T]":
"""
Filter the value of the Maybe, returning Nothing if the predicate returns False.
Analogous to `Option::filter` in Rust.
>>> Just(1).filter(lambda x: x > 1)
Nothing()
>>> Just(1).filter(lambda x: x < 1)
Nothing()
>>> Just(1).filter(lambda x: x == 1)
Just(1)
"""
...

@abstractmethod
def to_optional(self) -> Optional[T]:
"""
Expand Down Expand Up @@ -201,6 +217,9 @@ def unwrap_or(self, default: T) -> T:
def unwrap_or_else(self, f: Callable[[], T]) -> T:
return self.value

def filter(self, f: Callable[[T], bool]) -> Maybe[T]:
return self if f(self.value) else Nothing()

def to_optional(self) -> T:
return self.value

Expand Down Expand Up @@ -276,6 +295,9 @@ def unwrap_or(self, default: T) -> T:
def unwrap_or_else(self, f: Callable[[], T]) -> T:
return f()

def filter(self, f: Callable[[T], bool]) -> "Nothing[T]":
return Nothing()

def to_optional(self) -> None:
return None

Expand Down
6 changes: 6 additions & 0 deletions tests/test_maybe.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ def test_unwrap_or():
assert Nothing().unwrap_or(2) == 2


def test_filter():
assert Just(1).filter(lambda x: x > 1) == Nothing()
assert Just(1).filter(lambda x: x < 1) == Nothing()
assert Just(1).filter(lambda x: x == 1) == Just(1)


def test_from_try():
assert Maybe.from_try(lambda: 1 / 1, ZeroDivisionError) == Just(1)
assert Maybe.from_try(lambda: 1 / 0, ZeroDivisionError) == Nothing()
Expand Down

0 comments on commit a3dda3a

Please sign in to comment.