RussAbbott
RussAbbott

Reputation: 2738

How to represent a parameterized type in Python?

In Haskell, foldm (the monad version of foldl) has this type.

foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a

(See this, for example.)

A Python equivalent might be declared like this.

a = TypeVar('a')
b = TypeVar('b')
def foldM(f: Callable[[a, b], Monad], acc: a, xs: List[b]) -> Monad:
    ...

A problem with this is that it doesn't show Monad as parameterized by type a. I'd like to write Monad[a], but that is not valid. Is there a way to do this?

Upvotes: 1

Views: 214

Answers (1)

gmds
gmds

Reputation: 19895

Have Monad inherit from Generic:

from typing import TypeVar, List, Callable, Generic

a = TypeVar('a')
b = TypeVar('b')

class Monad(Generic[a]):
    # your code here
    pass

def foldM(f: Callable[[a, b], Monad[a]], acc: a, xs: List[b]) -> Monad[a]:
    # your code here
    pass

Upvotes: 2

Related Questions