首页 > 解决方案 > JavaScript 中的任一类型实现

问题描述

在所有Either用 JavaScript 实现的库中,我注意到Either.of返回 a Right,我觉得我遗漏了一些关于为什么会这样的东西,有人知道吗?此外,我对实现的直觉Either类似于new Either(true, 'foo')for arightnew Either(false, 'err')for aleft并且可能有静态方法Either.rightEither.left但所有库似乎都有一个基类Either和子类,Left而且Right我也觉得我错过了为什么他们中的大多数决定用继承来实现它?

标签: javascriptfunctional-programmingeither

解决方案


要么是一个简单的原型 Sum 类型。这就像一个 IF-ELSE-THEN 构造函数(EITHER-LEFT-RIGHT)。

因此,该构造either接收带有值的 Left 或 Right。这是纯 Javascript 中 Left、Right 和 Either 的函数方法。

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

旁注:您不需要该功能either,因为如果您应用 Beta-Reduction,您会看到either === identity。它只是语法糖。

我给你一个更好的例子并构建一个函数来检查参数是否为整数值并将其返回

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

希望这能让您更好地了解FP 中的任何一个。

顺便一提。使用任何一种方法,您都可以轻松构建 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) )

推荐阅读