Skip to main content

A library that encapsulates stateful computations into a monadic structure.

Project description

State-Monad

State-Monad is a Python library that encapsulates stateful computations into a monadic structure.

Overview

The state object (also referred to as a context) is a Python object that represents the state in your computations. Each operation may modify the state and return a new values based on the updated state. The result is a chain of operations where the state flows through each step, with the State-Monad keeping the flow clean and organized.

Example

In this example, we define the collect_even_numbers operations, which returns a CollectEvenNumbers state monad if the given number is even, or a default state monad encapsulating the value otherwise. The example function performs monadic operations using the collect_even_numbers operator, resulting in a state monad. Finally, the constructed state monad is applied with an empty tuple as the initial state.

from dataclassabc import dataclassabc

import statemonad
from statemonad.abc import StateMonadNode
from statemonad import init_state_monad


type State = tuple[int, ...]
state = tuple()


def collect_even_numbers(num: int):
    """
    This function encapsulates the given number within a state monad 
    and saves it to the state if the number is even.
    """
    
    if num % 2 == 0:

        @dataclassabc(frozen=True)
        class CollectEvenNumbers(StateMonadNode[State, int]):
            num: int

            def apply(self, state: State):
                n_state = state + (self.num,)
                return n_state, self.num

        return init_state_monad(CollectEvenNumbers(num=num))

    else:
        return statemonad.from_[State](num)

# do some monadic operations using `flat_map`
def example(init):
    return collect_even_numbers(init + 1).flat_map(
        lambda x: collect_even_numbers(x + 1).flat_map(
            lambda y: collect_even_numbers(y + 1).flat_map(
                lambda z: collect_even_numbers(z + 1)
            )
        )
    )

monad = example(3)

# Output will be
# monad=StateMonadImpl(
#   child=FlatMapImpl(
#       child=CollectEvenNumbers(num=4),
#   func=<function example.<locals>.<lambda> at 0x000001A546B53D80>))
print(f"{monad=}")

state, value = monad.apply(state)

print(f"{value=}")  # Output will be value=7
print(f"{state=}")  # Output will be state=(4, 6)

Note that defining the CollectEvenNumbers state monad as its proper class, enables us to nicely print the representation of the resulting Python object. Unfortunately, parts of the representation is hidden behind the lambda function given to the flat_map method.

Do-notation

Using the donotation library, the monadic sequence above can be rewritten with the do-notation as follows:

@do()
def example(init):
    x = yield from collect_even_numbers(init + 1)
    y = yield from collect_even_numbers(x + 1)
    z = yield from collect_even_numbers(y + 1)
    return collect_even_numbers(z + 1)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

statemonad-0.0.1.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

statemonad-0.0.1-py3-none-any.whl (15.0 kB view details)

Uploaded Python 3

File details

Details for the file statemonad-0.0.1.tar.gz.

File metadata

  • Download URL: statemonad-0.0.1.tar.gz
  • Upload date:
  • Size: 9.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for statemonad-0.0.1.tar.gz
Algorithm Hash digest
SHA256 3680e54c1489b4fe03f981f80e04319fa5b56ed3eebe079f05665d3a9f27a4e5
MD5 44aab112bc2fbd15dc5e88f583e0cef2
BLAKE2b-256 f86fbcc13ae8db09d40723317e4447694e52d9d3649e515b72cb42a0d813e777

See more details on using hashes here.

File details

Details for the file statemonad-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: statemonad-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 15.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for statemonad-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3c4737880320dc782463329225cd01c5066bf587a7f114d788e14bb7f166c05b
MD5 2db70f2c98bcba7a1b8884c8bdcdd942
BLAKE2b-256 73a45a4443732fa27c0aa4cfc6f33f3e74b21c10941c2b42339b397f201ac023

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page