jasondelaat / pymonad

PyMonad implements data structures typically available in pure functional or functional first programming languages like Haskell and F#. Included are Monad and Monoid data types with several common monads included - such as Maybe and State - as well as some useful tools such as the @curry decorator for defining curried functions. PyMonad 2.x.x represents an almost complete re-write of the library with a simpler, more consistent interface as well as type annotations to help ensure correct usage.
BSD 3-Clause "New" or "Revised" License
198 stars 22 forks source link

Please add or_else #29

Open juxeii opened 1 year ago

juxeii commented 1 year ago

Hi,

could you please add or_else to the Maybe monad?

chuckwondo commented 1 year ago

@jasondelaat, thank you for this fantastically useful, yet unbloated, library!

I would like to see this for Either as well, but perhaps instead of defining new methods, the Maybe.maybe and Either.either methods can simply be modified (since they appear to simply be or_else named differently) such that the identity function is the default value for the second argument to those methods, since that is arguably the most common use case, and having to repeat lambda x: x (or identity, if that is defined somewhere) is tiresome and unnecessarily verbose.

For example:

class Maybe(pymonad.monad.Monad, Generic[T]):
    ...
    def maybe(self: 'Maybe[S]', default_value: T, extraction_function: Callable[[S], T] = lambda x: x) -> T:
        ...

class Either(pymonad.monad.Monad, Generic[M, T]):
    ...
    def either(
            self: 'Either[M, S]', left_function: Callable[[M], T], right_function: Callable[[S], T] = lambda x: x
    ) -> T:
        ...
chuckwondo commented 1 year ago

I'd be happy to submit a PR, if this is something you're agreeable to.