Comments (5)
I'd also be curious to know why io-ts uses Either and not Validation?
That's a good question!
Either
, having a monad instance, is strictly more powerful than Validation
. You lose the ability to run validations in parallel but you gain the chainability of validations. There are many validations which can't be parallelized, for example integers
- first you must check that the input is a number
- then you must check that the number is an integer
That "then" requires the power of a monad and its chain
function
import { left, right } from 'fp-ts/lib/Either'
// any -> number
const isNumber = (input: any) => typeof input === 'number' ? right<string, number>(input) : left<string, number>('Not a number')
// number -> integer
const isNumberInteger = (input: number) => input % 1 === 0 ? right<string, number>(input) : left<string, number>('Not an integer')
// now I can compose the validations
// any -> integer
const isInteger = (input: any) => isNumber(input).chain(isNumberInteger)
console.log(isInteger('s')) // Left("Not a number")
console.log(isInteger(1.1)) // Left("Not an integer")
console.log(isInteger(1)) // Right(1)
I used the term "compose" because monads are a way to make composable a group of functions which naturally don't compose. Those functions, called Kleisli arrows, have the following general signature
A -> M<B>
b -> M<C>
where M
is a type constructor (kind * -> *
). In case of Either
we get (its left type is not important for what we are saying)
any -> Either<number>
number -> Either<integer>
From this point of view monads are pretty easy to explain: under the hood is just function composition (well to be precise is morphism composition).
This is a repo where I try to explain all these things (I put up a functional programming meet up here in Milano and the repo contains a series of lectures I gave during the last months)
Alas is in italian..
https://github.com/gcanti/functional-programming
from fp-ts.
@OliverJAsh
Try something like that (not tested)
const eitherToValidation = <L, A>(
leftSemigroup: StaticSemigroup<L>,
either: either.Either<L, A>,
): validation.Validation<L, A> =>
either.fold(
left => validation.failure<L, A>(leftSemigroup, left),
right => validation.success<L, A>(right),
)
Usage (with array):
eitherToValidation(array, either.left([10]))
from fp-ts.
For context, I am using io-ts which returns an Either
type, but I have a function that needs to return Validation
.
I'd also be curious to know why io-ts uses Either
and not Validation
? :-)
from fp-ts.
@OliverJAsh
You may use that one, it's more specific (force the usage of array) but may be handy.
const eitherToValidation = <L,A>(
either: either.Either<L, A>,
): validation.Validation<L[], A> =>
either.fold(
left => validation.failure<L[], A>(array, [left]),
right => validation.success<L[], A>(right),
)
Usage
eitherToValidation(either.left(10))
from fp-ts.
Super useful and insightful replies. Thank you! :-)
from fp-ts.
Related Issues (20)
- Type signature of RTE.tapReaderIO is wrong
- Either.Do: `left` to be structurally similar to `right` HOT 1
- 🐠 Give `map` the same overloaded signature as `flatMap` HOT 2
- record.modifyAt doesn't infer value type at given key HOT 4
- lookup types incorrect HOT 4
- [Question (feature?)] Clean way to define a Semigroup over a (partially) partial type HOT 1
- `readonlyNonEmptyArray.union()` should accept `ReadonlyArray` as second argument
- Why does `Json.stringify` return an `Either`? HOT 2
- Directory import is not supported resolving ES modules HOT 6
- Add installation instructions to the docs HOT 1
- Is the signature of TaskEither.tapError as intended? HOT 1
- Add tapNoneIO for Option, TaskOption and IOOption and tapErrorIO for Either, TaskEither and IOEither
- Comment-related warnings when building with Vite HOT 3
- Improving option.getOrElse type inference HOT 1
- How can I do recursion in an array and make the isShow flag true?
- Sequencing is incompatible with array.map
- Misplaced/useless PURE comments with latest vite/rollup HOT 1
- [ReadonlyArray.ts] `flatten` can trigger `RangeError: Maximum call stack size exceeded`
- Document how to make working with abstractions ergonomic
- warning about __PURE__ comment when building with vite + rollup
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fp-ts.