javascript - JavaScript 中的任一类型实现
问题描述
在所有Either
用 JavaScript 实现的库中,我注意到Either.of
返回 a Right
,我觉得我遗漏了一些关于为什么会这样的东西,有人知道吗?此外,我对实现的直觉Either
类似于new Either(true, 'foo')
for aright
和new Either(false, 'err')
for aleft
并且可能有静态方法Either.right
,Either.left
但所有库似乎都有一个基类Either
和子类,Left
而且Right
我也觉得我错过了为什么他们中的大多数决定用继承来实现它?
解决方案
要么是一个简单的原型 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) )
推荐阅读
- kubernetes - 如何在没有云提供商或 LB 的情况下获取 pod 内的客户端 ip
- javascript - 按下按钮后使用javascript打开表单
- firefox - 如何在firefox上使用javascript转换功能画中画
- java - 即使在 HotSpot 中没有带有 CMS 的 Full GC 的情况下,Old Generation 的大小如何减小?
- solr - 如何在 Hybris 的 Solr 更新中跳过坏文档
- grafana - InfluxDB 时间落后 15 分钟
- sql - 如何在Oracle中按日期分组和排序?
- c - 为什么我得到 SIGABRT?
- amazon-web-services - 清理 AWS CodePipeline 中的旧文件
- algorithm - 快速排序代码之间的区别