Created
September 9, 2022 22:08
-
-
Save GongYiLiao/992a9da3a956f2c6a18a0f76037eb660 to your computer and use it in GitHub Desktop.
Trun Python into Haskell - a test
This file contains hidden or 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 itertools import islice | |
| from typing import TypeVar, NoReturn | |
| from collections.abc import Callable, Generator, Sequence, Iterable | |
| T = TypeVar('T') | |
| def gfib(f: Callable[[Sequence[T]], T], | |
| xs:Sequence[T]) -> Generator[T]: | |
| while True: | |
| x, *xs = *xs, f(xs) | |
| yield x | |
| def itake(n: int, | |
| ys: Iterable[T]) -> list[T]: | |
| if isinstance(n, int) and (n >= 1): | |
| return list(islice(ys, n)) | |
| else: | |
| raise ValueError("n must be a integer greater than 0.") | |
| class GfibSeq(object): | |
| def __init__(self, | |
| f: Callable[[Sequence[T]], T], | |
| xs: Sequence[T]) -> NoReturn: | |
| self.__gen = gfib(f, xs) | |
| self.__xs = [] | |
| def take(self, n: int) -> list[T]: | |
| if len(self.__xs) < n: | |
| self.__xs = self.__xs + itake(n - len(self.__xs), self.__gen) | |
| return self.__xs[:n] | |
| def nth(self, n: int) -> T: | |
| self.take(n + 1)[-1] | |
| # gfib.py ends here |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Few things are left: