Skip to content
This repository was archived by the owner on Jul 12, 2025. It is now read-only.
This repository was archived by the owner on Jul 12, 2025. It is now read-only.

How to aggregate all success/failures in list of Validation (sequence?)Β #71

Closed

Description

@OliverJAsh

Hi, thanks for the fantastic library and learning resources.

I have Array<Validation<A, B>> and want to aggregate all the successes and failures, e.g. Array<Validation<A, B>> => Validation<Array<A>, Array<B>>.

I thought this was possible using control.monads.sequence, however I seem to get runtime error mr.chain is not a function, so I presume I must be doing something wrong.

I have had success sequencing a list of Eithers, but in my case I want to aggregate the left hand side as well, which from reading this blog post, it appears Validation should help.

Thanks!

Activity

  1. OliverJAsh commented on Feb 4, 2017

    @OliverJAsh
    Author

    Never mind, got it now!

    // Array<Validation<A, B>> => Validation<Array<A>, Array<B>>
    const sequenceValidations = validations => (
        validations
            .reduce((acc, validation) => (
                Validation.Success(a => b => a.concat(b)).ap(acc).ap(validation)
            ), Validation.of([]))
    )

    Is this function in the library anywhere?

  2. robotlolita commented on Feb 5, 2017

    @robotlolita
    Member

    @OliverJAsh Validations implement Applicative, rather than Monad, so sequence (which uses the Monad's interface .chain) doesn't work on them.

    There isn't a function to aggregate Validations yet. Validations themselves already aggregate failures when you use .apply(), but the failure needs to have a .concat method. You can write a function to do this as:

    const Validation = require('folktale/data/validation');
    const curry = require('folktale/core/lambda/curry');
    
    const intoArray = (x) => Array.isArray(x) ? x : [x];
    
    const collect = (validations) =>
      validations.map(x => x.failureMap(intoArray)).reduce(
        (a, b) => a.ap(b),
        Validation.of(curry(validations.length, (...values) => values))
      );

    So something like:

    collect([a, b, c]);

    Translates to:

    Validation.of((a, b, c) => [a, b, c])
      .ap(a.failureMap(intoArray))
        .ap(b.failureMap(intoArray))
          .ap(c.failureMap(intoArray))
  3. added this to the v2.0.0 milestone on Feb 5, 2017
  4. self-assigned this
    on Mar 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions