pythonhaskellfunctional-programmingpython-typing

Is it possible to properly type hint the filterM function in Python?


I'm currently self-studying functional programming by writing a monad library in python. And I'm having trouble with type hinting. So for example, there is a function filterM in Haskell with signature

filterM :: (a -> m Bool) -> [a] -> m [a]

Ideally, if python can pattern match "subtypes" of a TypeVar by putting a bracket after it, then I should be able to do it with something like this:

T = TypeVar('T')
M = TypeVar('M', bound=Monad)
def filterM(filter_func: Callable[[T], M[bool]], iterable: list[T]) -> M[list[T]]

But it seems that the above syntax wouldn't work. In fact, it seems like there is no way to "extract" the type of monad I pass in at all. Say I pass in a Callable[[int], Maybe[bool]], the best I achieved was to take the whole Maybe[bool] as a single TypeVar. Then there is no way to convert it to the correct output type Maybe[list[int]].


Solution

  • Currently, what you want cannot be done. You'll have to make a plan that doesn't require it.