Skip to content

Instantly share code, notes, and snippets.

@GongYiLiao
Created September 9, 2022 22:08
Show Gist options
  • Select an option

  • Save GongYiLiao/992a9da3a956f2c6a18a0f76037eb660 to your computer and use it in GitHub Desktop.

Select an option

Save GongYiLiao/992a9da3a956f2c6a18a0f76037eb660 to your computer and use it in GitHub Desktop.
Trun Python into Haskell - a test
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
@GongYiLiao
Copy link
Author

Few things are left:

  • No Monad yet
  • ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment