In all the libraries implementing Either in JavaScript, I notice that Either.of returns a Right, I feel that I'm missing something about why that is, does anyone know? Also my intuition for an Either implementation is something like new Either(true, 'foo') for a right and new Either(false, 'err') for a left and maybe have static methods like Either.right and Either.left but all the libraries seem to have a base class Either and sub classes Left and Right, I also feel that I'm missing something about why most of them decided to implement it with inheritance?
1 Answer
Either is a simple prototypical Sum Type. It's like a IF-ELSE-THEN Constructor (EITHER-LEFT-RIGHT).
So, the construct either recieve either a Left or Right with value.
Here is the functional approache of Left, Right and Either in pure Javascript.
const Left = x => f => g => f (x);
const Right = x => f => g => g (x);
const either = e => f => g => e (f) (g);
// example:
either( Left(0) )(x => x + 1)(x => x-1) // 1
either( Right(0) )(x => x + 1)(x => x-1) // -1
Sidenote:
You do not need the function either, because if you would apply Beta-Reduction you will see that either === identity. It is just syntactic sugar.
I give you a better example and build a function that check if the argument is a Integer value or not and return it as either:
const eitherJsNumOrOther = val =>
Number.isInteger(val)
? Right(val)
: Left(`${val}, is not a integer`);
// either function left-case right-case
eitherJsNumOrOther( 10 )(console.error)(x => x + 5) // 15
eitherJsNumOrOther("bla")(console.error)(x => x + 5) // prints to console: bla, is not a integer
Hope that gives you a better understanding about either in the FP.
By the way. With either you can easy build the Maybe-Type.
const Nothing = Left();
const Just = Right ;
const maybe = either;
// and can use the either construct for a maybe-Number-Function for example
const maybeNumber = val =>
eitherJsNumOrOther(val)
( Nothing )
( Just(val) )
Either(false, 'err') || Either(true, 'foo')ofas a computation that has the potential for an effect. What isEither's effect? Unwind the stack and yield an error message (please note thatEithercan also be used more generally). Ifofyields aLefteach invocation would actually perform the effect. This would be far less useful. We only want the potential for the effect, which meansofis hypothetically capable of throwing an error, because it is of typeEither, but in reality it never does.ofas a way to get the computation going, I mean from something that is definitively aRight