dbrattli / Expression

Functional programming for Python
https://expression.readthedocs.io
MIT License
502 stars 32 forks source link

Any data type / structure for error accumulation? #230

Open vreuter opened 5 days ago

vreuter commented 5 days ago

Is there any structure with which to accumulate errors from multiple Results? Say I have a dataclass with three fields and each needs validation, and I'd like to take input and either emit a Result.Ok with an instance of my dataclass, or a Result.Error with a collection of the (one or more) errors from the (failed) validation of the input.

Something from Scala might looks like...

case class Mine(a: A, b: B, c: C)

def safeA: String => Either[String, A]
def safeB: String => Either[String, B]
def safeC: String => Either[String, C]

def safeBuild(s1: String, s2: String, s2: String): cats.data.ValidatedNel[String, Mine] = 
  val aNel = safeA(s1).toValidatedNel
  val bNel = safeB(s2).toValidatedNel
  val cNel = safeC(s3).toValidatedNel
  (aNel, bNel, cNel).mapN(Mine.apply)

So I guess I'm looking for something like...

from dataclasses import dataclass

@dataclass
class Mine:
    a: int
    b: float
    c: str

def maybeA(s: str) -> Result[int, str]: ...
def maybeB(s: str) -> Result[float, str]: ...
def maybeC(s: str) -> Result[str, str]: ...

def maybeMine(s1: str, s2: str, s3: str) -> Result[Mine, list[str]]:
    ??? # how to combine the application of each component's safe parser?
vreuter commented 5 days ago

Would be powered by #215