Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Math operations #1

Closed
thepabloaguilar opened this issue Jul 9, 2020 · 1 comment · Fixed by #3
Closed

Math operations #1

thepabloaguilar opened this issue Jul 9, 2020 · 1 comment · Fixed by #3

Comments

@thepabloaguilar
Copy link
Member

Hello, I'm opening this issue to discuss about Math operations. I've had and initial idea!

Create an class, MathOperations or something like, it'll store all operations to be executed when __call__ is called! So the math operations from _Callable will return that class.
I've made a simple test without the class:

>>> import operation
>>> from lambdas import _fmap

>>> # _ + 1 - 10
>>> operations = [_fmap(operator.add)(None, 1), _fmap(operator.sub)(None, 10)]
>>> first_operation, *rest_operations = operations
>>> reduce(lambda partial_result, operation: operation(partial_result), rest_operations, first_operation(1))
-8

I was worried about the operations order, but Python does it for us!

>>> # If we have this `_ + 1 * 2`, the operations list should be like below
>>> operations = [_fmap(operator.add)(None, 3)]

Python deals with the operations order, we just have to store them.

@thepabloaguilar
Copy link
Member Author

I've implemented a test:

class MathOperations:
    def __init__(self) -> None:
        self._operations = []

    def _add_operation(self, operation, other):
        self._operations.append(partial(operation, other))
        return self

    def __add__(self, other):
        return self._add_operation(operator.add, other)

    def __mul__(self, other):
        return self._add_operation(operator.mul, other)

    def __sub__(self, other):
        return self._add_operation(operator.sub, other)

    def __mod__(self, other):
        return self._add_operation(operator.mod, other)

    def __pow__(self, other):
        return self._add_operation(operator.pow, other)

    def __call__(self, number):
        first_operation, *rest_operations = self._operations
        return reduce(
            lambda partial_result, operation: operation(partial_result),
            rest_operations,
            first_operation(number)
        )


class _Callable(object):
    def __add__(self, other) -> Callable[['_Callable', T1], Callable[[T1], T1]]:
        return MathOperations() + other
>>> from lambdas import _

>>> func_one = _ + 1 * 10
>>> func_two = (_ + 1) * 10

>>> func_one(1)
1
>>> func_two(1)
20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

1 participant