system-f / validation

A data-type like Either but with an accumulating Applicative
Other
99 stars 28 forks source link

Add a lazier version #53

Open treeowl opened 3 years ago

treeowl commented 3 years ago

In case of failure, one may be interested in only the first few errors, but Validation requires that everything be checked regardless. A version with a Monoid rather than Semigroup constraint could allow this in the list monoid with something like

liftA2 _ (Failure e1) m = Failure $ e1 <> case m of
  Failure es -> es
  Success _ -> mempty
tonymorris commented 3 years ago

Good point!

treeowl commented 3 years ago

In think in principle, neither Semigroup nor Monoid is the right underlying class when taking laziness into account.

class Accumulate a where
  accum :: a -> Maybe a -> a

newtype Semi a = Semi { unSemi :: a }
newtype Mon a = Mon { unMon :: a }

instance Semigroup a => Accumulate (Semi a) where
  accum a (Just b) = a <> b
  accum a Nothing = a

instance Monoid a => Accumulate (Mon a) where
  accum a mb = a <> maybe mempty id mb
tonymorris commented 2 years ago

Has this class been published?

treeowl commented 2 years ago

Not that I know of. It's an oddball. I think it would likely be best to just add the lazier, Monoid-based version of Validation as Data.Validation.Lazy.