Skip to content

Instantly share code, notes, and snippets.

@boechat107
Last active January 3, 2020 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boechat107/9d921ec08ef8a52468bfced78785654a to your computer and use it in GitHub Desktop.
Save boechat107/9d921ec08ef8a52468bfced78785654a to your computer and use it in GitHub Desktop.
Functional Programming with type annotation in Python
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