是否可以在Python中正确键入提示filterM函数?

Tia*_*eng 5 python haskell functional-programming type-hinting

我目前正在通过用 python 编写 monad 库来自学函数式编程。我在类型提示方面遇到了麻烦。例如,Haskell中有一个带有签名的函数filterM

filterM :: (a -> m Bool) -> [a] -> m [a]
Run Code Online (Sandbox Code Playgroud)

理想情况下,如果 python 可以通过在 TypeVar 后面放一个括号来模式匹配 TypeVar 的“子类型”,那么我应该能够用这样的方法来做到这一点:

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

但上面的语法似乎不起作用。事实上,似乎根本没有办法“提取”我传入的 monad 类型。假设我传入 a Callable[[int], Maybe[bool]],我取得的最好成绩是将整个Maybe[bool]作为单个 TypeVar 。那么就没有办法将其转换为正确的输出类型Maybe[list[int]]

Dan*_*ner 4

目前,你想要的还无法实现。你必须制定一个不需要它的计划。