Last active
January 3, 2020 14:36
-
-
Save boechat107/9d921ec08ef8a52468bfced78785654a to your computer and use it in GitHub Desktop.
Functional Programming with type annotation in Python
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
from typing import Callable, Iterable, TypeVar, Iterator, Optional | |
A = TypeVar("A") | |
def some(pred: Callable[[A], bool], seq: Iterable[A]) -> Optional[A]: | |
""" | |
Returns the first item in "seq" that satisfies "pred". | |
Examples: | |
fp.some(lambda x: x > 2, [1, 0, 3, 2]) | |
> 3 | |
fp.some(lambda x: x > 2, [1, 0, 2, 2]) | |
> None | |
""" | |
def recur(seqiter: Iterator[A]) -> Optional[A]: | |
try: | |
item = next(seqiter) | |
except StopIteration: | |
return None | |
return item if pred(item) else recur(seqiter) | |
return recur(iter(seq)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment