Types Module¶
Concrete type implementations with algebraic properties.
This module provides immutable data structures that implement the algebraic
abstractions from katharos.algebra. These types enable type-safe,
composable functional programming patterns.
- Available types:
Maybe: Optional values without None checksResult: Error handling without exceptionsImmutableList: Immutable list with monadic operationsNonEmptyList: List guaranteed to have at least one elementIO: Lazy computation with side effectsMonoidMaybe: Maybe with monoid instance
Each type implements appropriate algebraic abstractions (Functor, Applicative, Monad, etc.) and provides operators for convenient composition.
Maybe¶
- final class katharos.types.Maybe(value=Nothing())[source]¶
Bases:
Monad[Maybe[Any],A]Optional value monad for type-safe null handling.
Maybeencapsulates a value that may or may not be present, eliminatingNonechecks through functional composition. It implements theMonad,Applicative, andFunctorinterfaces.A
Maybeis in one of two states:Just: contains a value of type
A.Nothing: contains no value.
Use
Just()andNothing()to construct values. Useis_just()andis_nothing()to check the state rather thanisinstancechecks.Examples
>>> Maybe.Just(5).fmap(lambda x: x * 2) Just(10)
>>> Maybe.Nothing().fmap(lambda x: x * 2) Nothing()
>>> Maybe.Just(3) | (lambda x: Maybe.Just(x + 1)) Just(4)
Note
This class is
@finaland cannot be subclassed. Supports the|(bind) and**(applicative apply) operators.- classmethod ret(x)[source]¶
Wrap a value in a Just.
Alias for
pure(), provided to satisfy the Monad interface.
- __init__(value=Nothing())[source]¶
Initialize a Maybe with an optional value.
- Parameters:
value (
Union[TypeVar(A, covariant=True),_Nothing]) – The value to wrap. Defaults tonothing.
- unwrap()[source]¶
Extract the wrapped value.
- Return type:
TypeVar(A, covariant=True)- Returns:
The value contained in this Maybe.
- Raises:
ValueError – If this Maybe is Nothing.
- is_just()[source]¶
Check if this Maybe contains a value.
- Return type:
- Returns:
True if this is a Just, False if it is Nothing.
- is_nothing()[source]¶
Check if this Maybe contains no value.
- Return type:
- Returns:
True if this is Nothing, False if it is a Just.
MonoidMaybe¶
- class katharos.types.MonoidMaybe(maybe)[source]¶
Bases:
Monoid[MonoidMaybe[A]],GenericA
Monoidinstance for optional semigroup values.Lifts a semigroup
Ainto an optional context: twoJustvalues are combined using their semigroup@operation;Nothingacts as the identity element, leaving the other operand unchanged.- classmethod identity()[source]¶
Return the identity element of the MonoidMaybe monoid.
- Return type:
MonoidMaybe[TypeVar(A, bound=Semigroup)]- Returns:
A MonoidMaybe wrapping Nothing, which acts as the identity.
- property maybe: Maybe[A]¶
The wrapped Maybe value.
- Returns:
The Maybe value held by this MonoidMaybe.
- op(other)[source]¶
Combine this MonoidMaybe with another using the semigroup operation.
- Parameters:
other (
MonoidMaybe[TypeVar(A, bound=Semigroup)]) – Another MonoidMaybe to combine with.- Return type:
MonoidMaybe[TypeVar(A, bound=Semigroup)]- Returns:
The other operand if this is Nothing; this operand if other is Nothing; otherwise a MonoidMaybe wrapping
Just(self @ other).
Result¶
- final class katharos.types.Result(value)[source]¶
Bases:
Generic[E,A],Monad[Result[E, Any],A]A Result monad for error handling without exceptions.
The Result type encapsulates a computation that can either succeed with a value of type A or fail with an exception of type E. It implements the Monad, Applicative, and Functor interfaces for composable error handling.
A Result can be in one of two states:
Success: Contains a value of type
A(non-exception)Failure: Contains an exception of type
E
Type Parameters:
E: The type of the exception (must be a subclass ofBaseException).A: The type of the success value.
Examples
>>> success = Result.Success(42) >>> success.is_success() True >>> success Success(42) >>> success.value 42
>>> failure = Result.Failure(ValueError("error")) >>> failure.is_failure() True >>> failure Failure(ValueError('error')) >>> failure.error ValueError('error')
>>> success.fmap(lambda x: x * 2) Success(84)
>>> failure.fmap(lambda x: x * 2) Failure(ValueError('error'))
>>> Result.Success(5) | (lambda x: Result.Success(x + 1)) Success(6)
Note
This class is marked as
@finaland cannot be subclassed. Useis_success()andis_failure()methods to check the state instead of type checking. UseSuccess()to create success values andFailure()to create failure values. Access success values with.valueand failure errors with.error.The class supports the following operators:
|(pipe): Monadic bind operation.**(power): Applicative application.
- classmethod pure(x)[source]¶
Wrap a value in a Success.
- Parameters:
x (
TypeVar(T)) – The value to wrap.- Returns:
A Success containing the value.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(T)]- Raises:
TypeError – If the value is an exception.
Examples
>>> Result.pure(42) Success(42)
>>> Result.pure("hello") Success('hello')
>>> Result.pure(ValueError("oops")) Traceback (most recent call last): ... TypeError: Cannot create a Result with an exception as the value
- classmethod ret(x)[source]¶
Wrap a value in a Success.
Alias for
pure(), provided to satisfy the Monad interface.- Parameters:
x (
TypeVar(T)) – The value to wrap.- Returns:
A Success containing the value.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(T)]- Raises:
TypeError – If the value is an exception.
Examples
>>> Result.ret(42) Success(42)
- static Success(x)[source]¶
Create a Success result.
- Parameters:
x (
TypeVar(A, covariant=True)) – The value to wrap.- Returns:
A Success result containing the value.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(A, covariant=True)]
Examples
>>> Result.Success(42) Success(42)
>>> Result.Success([1, 2, 3]) Success([1, 2, 3])
- static Failure(e)[source]¶
Create a Failure result.
- Parameters:
e (
TypeVar(E, bound=BaseException, covariant=True)) – The exception to wrap.- Returns:
A Failure result containing the exception.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(A, covariant=True)]- Raises:
TypeError – If the value is not an exception.
Examples
>>> Result.Failure(ValueError("bad input")) Failure(ValueError('bad input'))
>>> Result.Failure(42) Traceback (most recent call last): ... TypeError: Cannot create a Result with a non-exception as the value
- __init__(value)[source]¶
Initialize the Result.
- Parameters:
value (
Union[TypeVar(A, covariant=True),TypeVar(E, bound=BaseException, covariant=True)]) – The value to wrap, either A or E.
- property value: A¶
Get the success value of the Result.
- Returns:
The success value.
- Return type:
A
- Raises:
TypeError – If the Result is a Failure.
Examples
>>> Result.Success(42).value 42
>>> Result.Failure(ValueError("err")).value Traceback (most recent call last): ... TypeError: Cannot get the value of a Failure
- property error: E¶
Get the error of the Result.
- Returns:
The exception value.
- Return type:
E
- Raises:
TypeError – If the Result is a Success.
Examples
>>> Result.Failure(ValueError("err")).error ValueError('err')
>>> Result.Success(42).error Traceback (most recent call last): ... TypeError: Cannot get the error of a Success
- unwrap()[source]¶
Unwrap the success value, raising an error if this is a Failure.
This method extracts the success value from a Success Result. If the Result is a Failure, it raises a TypeError with the original exception as the cause.
This is equivalent to accessing the
.valueproperty directly.- Returns:
The success value contained in this Result.
- Return type:
TypeVar(A, covariant=True)- Raises:
TypeError – If the Result is a Failure, with the original exception as the cause chain.
Examples
>>> success = Result.Success(42) >>> success.unwrap() 42
>>> failure = Result.Failure(ValueError("error")) >>> failure.unwrap() Traceback (most recent call last): ... TypeError: Cannot get the value of a Failure
- fmap(f)[source]¶
Map a function over the success value.
- Parameters:
f (
Callable[[TypeVar(A, covariant=True)],TypeVar(B)]) – Function to apply to the value.- Returns:
- A new Result containing the mapped value, or the
original Failure unchanged.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(B)]
Examples
>>> Result.Success(3).fmap(lambda x: x * 2) Success(6)
>>> Result.Failure(ValueError("err")).fmap(lambda x: x * 2) Failure(ValueError('err'))
>>> Result.Success("hi").fmap(str.upper) Success('HI')
- ap(wrapped_funcs)[source]¶
Apply a function wrapped in a Result to this Result.
- Parameters:
wrapped_funcs (
Applicative[Result[TypeVar(E, bound=BaseException, covariant=True),Any],Callable[[TypeVar(A, covariant=True)],TypeVar(B)]]) – A Result containing the function to apply.- Returns:
- The result of applying the wrapped function to this
value, or the first encountered Failure.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(B)]
Examples
>>> wrapped_fn = Result.Success(lambda x: x + 1) >>> Result.Success(5).ap(wrapped_fn) Success(6)
>>> Result.Failure(ValueError("err")).ap(wrapped_fn) Failure(ValueError('err'))
>>> failure_fn = Result.Failure(TypeError("bad fn")) >>> Result.Success(5).ap(failure_fn) Failure(TypeError('bad fn'))
- bind(f)[source]¶
Bind a function that returns a Result to this Result.
- Parameters:
f (
Callable[[TypeVar(A, covariant=True)],Monad[Result[TypeVar(E, bound=BaseException, covariant=True),Any],TypeVar(B)]]) – A function that takes a value of type A and returns a Result of type B.- Returns:
- The result of applying the function to the success
value, or the original Failure unchanged.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(B)]
Examples
>>> Result.Success(5).bind(lambda x: Result.Success(x + 1)) Success(6)
>>> Result.Success(5).bind(lambda x: Result.Failure(ValueError("nope"))) Failure(ValueError('nope'))
>>> Result.Failure(ValueError("err")).bind(lambda x: Result.Success(x + 1)) Failure(ValueError('err'))
- is_success()[source]¶
Check if this Result is a Success.
- Returns:
True if this is a Success, False otherwise.
- Return type:
Examples
>>> Result.Success(42).is_success() True
>>> Result.Failure(ValueError("err")).is_success() False
- is_failure()[source]¶
Check if this Result is a Failure.
- Returns:
True if this is a Failure, False otherwise.
- Return type:
Examples
>>> Result.Failure(ValueError("err")).is_failure() True
>>> Result.Success(42).is_failure() False
- __pow__(wrapped_funcs)[source]¶
Infix operator for applicative application (
**).- Parameters:
wrapped_funcs (
Applicative[Result[TypeVar(E, bound=BaseException, covariant=True),Any],Callable[[TypeVar(A, covariant=True)],TypeVar(B)]]) – A Result containing the function to apply.- Returns:
- The result of applying the wrapped function to this
value, or the first encountered Failure.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(B)]
Examples
>>> Result.Success(5) ** Result.Success(lambda x: x + 1) Success(6)
>>> Result.Failure(ValueError("err")) ** Result.Success(lambda x: x + 1) Failure(ValueError('err'))
- __or__(f)[source]¶
Infix operator for monadic bind (
|).- Parameters:
f (
Callable[[TypeVar(A, covariant=True)],Monad[Result[TypeVar(E, bound=BaseException, covariant=True),Any],TypeVar(B)]]) – A function that takes a value of type A and returns a Result of type B.- Returns:
- The result of applying the function to the success
value, or the original Failure unchanged.
- Return type:
Result[TypeVar(E, bound=BaseException, covariant=True),TypeVar(B)]
Examples
>>> Result.Success(5) | (lambda x: Result.Success(x + 1)) Success(6)
>>> (Result.Success(5) ... | (lambda x: Result.Success(x * 2)) ... | (lambda x: Result.Success(x - 1))) Success(9)
>>> Result.Failure(ValueError("err")) | (lambda x: Result.Success(x + 1)) Failure(ValueError('err'))
- __repr__()[source]¶
Return the string representation of the Result.
- Returns:
Success(<value>)orFailure(<error>).- Return type:
Examples
>>> repr(Result.Success(42)) 'Success(42)'
>>> repr(Result.Failure(ValueError("err"))) "Failure(ValueError('err'))"
- __eq__(value, /)[source]¶
Compare two Result objects for equality.
Two Results are equal if they are both Success with equal values, or both Failure with equal errors. A Result is never equal to a non-Result.
- Parameters:
value (
object) – The object to compare with.- Returns:
True if the objects are equal, False otherwise.
- Return type:
Examples
>>> Result.Success(42) == Result.Success(42) True
>>> Result.Success(42) == Result.Success(43) False
>>> err = ValueError("err") >>> Result.Failure(err) == Result.Failure(err) True
>>> Result.Success(42) == 42 False
- __hash__ = None¶
ImmutableList¶
- class katharos.types.ImmutableList(elements)[source]¶
Bases:
BaseImmutableList[T],Monad[ImmutableList[Any],T],Monoid[ImmutableList[T]]A covariant immutable list with full monad and monoid support.
Provides an immutable wrapper around a Python list. The type parameter
Tis covariant, soImmutableList[Child]is a subtype ofImmutableList[Parent]whenChildis a subtype ofParent.Instances are hashable and safe to use as dictionary keys or set members. All standard sequence operations are supported for read-only access.
Examples
>>> numbers = ImmutableList([1, 2, 3, 4, 5]) >>> len(numbers) 5 >>> 3 in numbers True >>> numbers[1] 2 >>> list(numbers) [1, 2, 3, 4, 5] >>> numbers + [6, 7] ImmutableList([1, 2, 3, 4, 5, 6, 7])
- __hash__()[source]¶
Return a hash of the list contents.
- Return type:
- Returns:
Hash of the element tuple.
- __repr__()[source]¶
Return the canonical string representation of this list.
- Return type:
- Returns:
ImmutableList([...])with the element list.
- __str__()[source]¶
Return the string form of the underlying element list.
- Return type:
- Returns:
The string representation of the internal Python list.
- __add__(other)[source]¶
Concatenate this list with another iterable.
- Parameters:
other (
Iterable[TypeVar(T, covariant=True)]) – The elements to append.- Return type:
ImmutableList[TypeVar(T, covariant=True)]- Returns:
A new ImmutableList containing elements from both sequences.
- classmethod identity()[source]¶
Return the identity element for the monoid operation.
- Return type:
ImmutableList[TypeVar(T, covariant=True)]- Returns:
An empty ImmutableList.
- classmethod pure(x)[source]¶
Wrap a single value in an ImmutableList.
- Parameters:
x (
TypeVar(T_1)) – The element to wrap.- Return type:
ImmutableList[TypeVar(T_1)]- Returns:
A singleton ImmutableList containing only
x.
- classmethod ret(x)[source]¶
Wrap a single value in an ImmutableList.
Alias for
pure(), provided to satisfy the Monad interface.- Parameters:
x (
TypeVar(T_1)) – The element to wrap.- Return type:
ImmutableList[TypeVar(T_1)]- Returns:
A singleton ImmutableList containing only
x.
- op(other)[source]¶
Combine this list with another using concatenation.
- Parameters:
other (
ImmutableList[TypeVar(T, covariant=True)]) – Another ImmutableList to concatenate with.- Return type:
ImmutableList[TypeVar(T, covariant=True)]- Returns:
A new ImmutableList containing elements from both lists.
- fmap(f)[source]¶
Map a function over every element.
- Parameters:
f (
Callable[[TypeVar(T, covariant=True)],TypeVar(B)]) – A function to apply to each element.- Return type:
ImmutableList[TypeVar(B)]- Returns:
A new ImmutableList with the function applied to each element.
- ap(wrapped_funcs)[source]¶
Apply each wrapped function to each element (cartesian product).
- Parameters:
wrapped_funcs (
Applicative[ImmutableList,Callable[[TypeVar(T, covariant=True)],TypeVar(B)]]) – An ImmutableList of functions to apply.- Return type:
ImmutableList[TypeVar(B)]- Returns:
A new ImmutableList with results of applying every function to every element.
- bind(f)[source]¶
Flatmap this list with a function that returns a list (concatMap).
- Parameters:
f (
Callable[[TypeVar(T, covariant=True)],Monad[ImmutableList,TypeVar(B)]]) – A function that takes an element and returns an ImmutableList.- Return type:
ImmutableList[TypeVar(B)]- Returns:
A new ImmutableList with the results of all returned lists concatenated.
- __matmul__(other)[source]¶
Infix operator for the semigroup concatenation (
@).- Parameters:
other (
ImmutableList[TypeVar(T, covariant=True)]) – Another ImmutableList to concatenate with.- Return type:
ImmutableList[TypeVar(T, covariant=True)]- Returns:
A new ImmutableList containing all elements from both lists.
- __pow__(wrapped_funcs)[source]¶
Infix operator for applicative application (
**).- Parameters:
wrapped_funcs (
Applicative[ImmutableList,Callable[[TypeVar(T, covariant=True)],TypeVar(B)]]) – An ImmutableList of functions to apply.- Return type:
ImmutableList[TypeVar(B)]- Returns:
A new ImmutableList with results of applying every function to every element.
- __or__(f)[source]¶
Infix operator for monadic bind (
|).- Parameters:
f (
Callable[[TypeVar(T, covariant=True)],Monad[ImmutableList,TypeVar(B)]]) – A function that takes an element and returns an ImmutableList.- Return type:
ImmutableList[TypeVar(B)]- Returns:
A new ImmutableList with all returned lists concatenated.
NonEmptyList¶
- class katharos.types.NonEmptyList(head, tail)[source]¶
Bases:
BaseImmutableList[T],Monad[NonEmptyList[Any],T],Semigroup[NonEmptyList[T]]An immutable list guaranteed to contain at least one element.
NonEmptyListprovides the same functional interface asImmutableList— includingMonadandSemigroup— without aMonoidinstance (no empty list is representable).Access the first element with
headand the remaining elements withtail.- __hash__()[source]¶
Return a hash of the list contents.
- Return type:
- Returns:
Hash of the element tuple.
- __add__(other)[source]¶
Concatenate this list with another iterable.
- Parameters:
other (
Iterable[TypeVar(T, covariant=True)]) – The elements to append.- Return type:
NonEmptyList[TypeVar(T, covariant=True)]- Returns:
A new NonEmptyList containing all elements from both sequences.
- __repr__()[source]¶
Return a string representation of this list.
- Return type:
- Returns:
NonEmptyList([...])with the element list.
- property head: T¶
The first element of the list.
- Returns:
The first element.
- property tail: list[T]¶
All elements after the first.
- Returns:
A plain list of the remaining elements (may be empty).
- classmethod pure(x)[source]¶
Wrap a single value in a NonEmptyList.
- Parameters:
x (
TypeVar(A)) – The element to wrap.- Return type:
NonEmptyList[TypeVar(A)]- Returns:
A singleton NonEmptyList containing only
x.
- classmethod ret(x)[source]¶
Wrap a single value in a NonEmptyList.
Alias for
pure(), provided to satisfy the Monad interface.- Parameters:
x (
TypeVar(A)) – The element to wrap.- Return type:
NonEmptyList[TypeVar(A)]- Returns:
A singleton NonEmptyList containing only
x.
- fmap(f)[source]¶
Map a function over every element.
- Parameters:
f (
Callable[[TypeVar(T, covariant=True)],TypeVar(B)]) – A function to apply to each element.- Return type:
NonEmptyList[TypeVar(B)]- Returns:
A new NonEmptyList with the function applied to each element.
- ap(wrapped_funcs)[source]¶
Apply each wrapped function to each element (cartesian product).
- Parameters:
wrapped_funcs (
Applicative[NonEmptyList,Callable[[TypeVar(T, covariant=True)],TypeVar(B)]]) – A NonEmptyList of functions to apply.- Return type:
NonEmptyList[TypeVar(B)]- Returns:
A new NonEmptyList with results of applying every function to every element.
- bind(f)[source]¶
Flatmap this list with a function that returns a NonEmptyList (concatMap).
- Parameters:
f (
Callable[[TypeVar(T, covariant=True)],Monad[NonEmptyList,TypeVar(B)]]) – A function that takes an element and returns a NonEmptyList.- Return type:
NonEmptyList[TypeVar(B)]- Returns:
A new NonEmptyList with the results of all returned lists concatenated.
- op(other)[source]¶
Concatenate this list with another NonEmptyList.
- Parameters:
other (
NonEmptyList[TypeVar(T, covariant=True)]) – Another NonEmptyList to combine with.- Return type:
NonEmptyList[TypeVar(T, covariant=True)]- Returns:
A new NonEmptyList containing all elements from both lists.
IO¶
- class katharos.types.IO(value, io_func=FunctionWithSideEffect(f=<function FunctionWithSideEffect.no_op.<locals>.<lambda>>, description='No operation'))[source]¶
Bases:
Monad[IO[Any],A]Lazy wrapper for a value with deferred side-effect execution.
IOencapsulates a value together with an optional side-effect function. The side effect is not run untilexecute()is called, preserving referential transparency for pure callers.Use
pure()orret()to create anIOwith no side effect,fmap()to transform the wrapped value, and|(orbind()) to sequence computations. Callexecute()to run accumulated side effects.- classmethod ret(x)[source]¶
Wrap a plain value in an IO action with no side effect.
Alias for
pure(), provided to satisfy the Monad interface.
- __init__(value, io_func=FunctionWithSideEffect(f=<function FunctionWithSideEffect.no_op.<locals>.<lambda>>, description='No operation'))[source]¶
Initialize an IO action.
- Parameters:
value (
TypeVar(A, covariant=True)) – The value to wrap.io_func (
FunctionWithSideEffect) – The side-effect function to defer. Defaults to a no-op.
- io_func: FunctionWithSideEffect¶
- property value: A¶
The value inside this IO action.
- Returns:
The wrapped value.