How to use the pfun.either.Left function in pfun

To help you get started, we’ve selected a few pfun examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github suned / pfun / tests / strategies.py View on Github external
def eithers(value_strategy=anything()):
    lefts = builds(Left, value_strategy)
    rights = builds(Right, value_strategy)
    return one_of(lefts, rights)
github suned / pfun / tests / test_effect.py View on Github external
def test_absolve(self):
        right = either.Right(1)
        left = either.Left('error')
        right_effect = effect.success(right)
        left_effect = effect.success(left)
        assert effect.absolve(right_effect).run(None) == 1
        with pytest.raises(Exception):
            # todo
            effect.absolve(left_effect).run(None)
github suned / pfun / pfun / files.py View on Github external
async def run_e(_) -> Trampoline[Either[OSError, None]]:
            try:
                with open(path, 'ab+') as f:
                    f.write(content)
                return Done(Right(None))
            except OSError as e:
                return Done(Left(e))
github suned / pfun / pfun / files.py View on Github external
async def run_e(_) -> Trampoline[Either[OSError, None]]:
            try:
                with open(path, 'w') as f:
                    f.write(content)
                return Done(Right(None))
            except OSError as e:
                return Done(Left(e))
github suned / pfun / pfun / effect.py View on Github external
async def run_e(r):
        return Done(Left(reason))
github suned / pfun / pfun / subprocess.py View on Github external
async def run_e(self):
            proc = await asyncio.create_subprocess_shell(
                cmd, stdin=stdin, stdout=stdout, stderr=stderr
            )
            stdout_, stderr_ = await proc.communicate()
            if proc.returncode != 0:
                return Done(
                    Left(
                        CalledProcessError(
                            proc.returncode, cmd, stdout_, stderr_
                        )
                    )
                )
            return Done(Right((stdout_, stderr_)))
github suned / pfun / pfun / either.py View on Github external
def decorator(*args, **kwargs) -> Either[Exception, A]:
        try:
            return Right(f(*args, **kwargs))
        except Exception as e:
            return Left(e)
github suned / pfun / pfun / maybe.py View on Github external
...         return Just(Right('Done'))
        ...     return Just(Left(i - 1))
        >>> tail_rec(f, 5000)
        Just('Done')

    Args:
        f: function to run "recursively"
        a: initial argument to `f`
    Return:
        result of `f`
    """
    maybe = f(a)
    if isinstance(maybe, Nothing):
        return maybe
    either = maybe.get
    while isinstance(either, Left):
        maybe = f(either.get)
        if isinstance(maybe, Nothing):
            return maybe
        either = maybe.get
    return Just(either.get)
github suned / pfun / pfun / either.py View on Github external
True if other is an `Left` instance and wraps the same \
            value as this instance, False otherwise
        """
        return isinstance(other, Left) and other.get == self.get

    def __bool__(self) -> bool:
        return False

    def and_then(self, f: Callable[[A], Either[B, C]]) -> Either[B, C]:
        return self

    def __repr__(self):
        return f'Left({repr(self.get)})'


Either = Union[Left[B], Right[A]]
"""
Type-alias for `Union[Left[TypeVar('L')], Right[TypeVar('R')]]`
"""
Either.__module__ = __name__


def either(f: Callable[..., A]) -> Callable[..., Either[A, B]]:
    """
    Turn ``f`` into a monadic function in the ``Either`` monad by wrapping
    in it a `Right`

    Example:
        >>> either(lambda v: v)(1)
        Right(1)

    Args:
github suned / pfun / pfun / result.py View on Github external
from functools import wraps
from typing import Callable, TypeVar, Union

from .either import Eithers, Left, Right, with_effect

A = TypeVar('A')
B = TypeVar('B')


class Ok(Right[A]):
    pass


class Error(Left[Exception]):
    get: Exception


Result = Union[Error, Ok[A]]

Results = Eithers[Exception, A, B]

with_effect = with_effect


def result(f: Callable[..., B]) -> Callable[..., Result[B]]:
    """
    Wrap a function that may raise an exception with a :class:`Result`.
    Can also be used as a decorator. Useful for turning
    any function into a monadic function