Skip to content
loading...

re: Getting started with fp-ts: Either vs Validation VIEW POST

FULL DISCUSSION
 

How would this look in 2.0.0-rc.7?
For starters getArraySemigroup and getApplicative seems to be missing :)

 

With fp-ts@2 will be something like

import { sequenceT } from 'fp-ts/lib/Apply'
import { Either, getValidation, left, map, mapLeft, right } from 'fp-ts/lib/Either'
import { getSemigroup, NonEmptyArray } from 'fp-ts/lib/NonEmptyArray'
import { pipe } from 'fp-ts/lib/pipeable'

const minLength = (s: string): Either<string, string> =>
  s.length >= 6 ? right(s) : left('at least 6 characters')

const oneCapital = (s: string): Either<string, string> =>
  /[A-Z]/g.test(s) ? right(s) : left('at least one capital letter')

const oneNumber = (s: string): Either<string, string> =>
  /[0-9]/g.test(s) ? right(s) : left('at least one number')

function lift<L, A>(
  check: (a: A) => Either<L, A>
): (a: A) => Either<NonEmptyArray<L>, A> {
  return a =>
    pipe(
      check(a),
      mapLeft(a => [a])
    )
}

function validatePassword(s: string): Either<NonEmptyArray<string>, string> {
  return pipe(
    sequenceT(getValidation(getSemigroup<string>()))(
      lift(minLength)(s),
      lift(oneCapital)(s),
      lift(oneNumber)(s)
    ),
    map(() => s)
  )
}

console.log(validatePassword('ab'))
/*
=> left([ 'at least 6 characters',
    'at least one capital letter',
    'at least one number' ])
*/
 

I've been following your blog series, and am keen to better understand how this applicative validation works so I pasted your sample above into my code. Unfortunately I get "Argument of type 'Either, [string, string, string]>' is not assignable to parameter of type 'unknown[]'." error on the sequenceT(getValidation...line above. Using fp-ts @ 2.2.0 and Typescript @ 3.7.3. What would be expecting a parameter of type unknown[]?

Sorry, I can't repro, the sample above looks fine

code of conduct - report abuse