我正在youtube上学习Bartosz的理论课。他将Const函子和恒等函子描述为“基本”函子可以从(对我来说可能是一种自由派的解释)派生出来。
我的问题,已经实现了ES6+ /幻想-土地(不重要的)版本的函子,一旦我开始集成为地图和管道的保护区libary。
实现非常简单
const {map: flMap, extract } = require('fantasy-land');
const getInstance = (self, constructor) =>
(self instanceof constructor) ?
self :
Object.create(constructor.prototype) ;
const Identity = function(x){
const self = getInstance(this, Identity)
self[flMap] = f => Identity(f(x))
self[extract] = () => x
return Object.freeze(self)
}以下是一些简单的用法(因为我也在使用离子衍生透镜)
// USAGE
const {map, pipe, curry} = require("sanctuary")
const extractFrom = x => x[extract]()
const setter = (f, x) => (pipe([
Identity,
map(f),
extractFrom
])(x))
const double = x => x + x
console.log(Identity(35)) //=> 35
console.log(map(double, Identity(35))) // ERROR Should be Identity(70)
console.log(setter(double, 35)) // ERROR Should be: 70TypeError:类型变量约束违反映射::函子f => (a -> b) -> f a -> f b^1 2 1) 35 ::Number,FiniteNumber,NonZeroFiniteNumber,Integer,NonNegativeInteger,ValidNumber 2) () => x ::Function,(c -> d) f =>恒等式(f(X)) ::函数,(c -> d)由于不存在所有上述值都是成员的类型,因此违反了类型变量约束。
然而,Const函子工作得更好一些(在map中没有调用f)
const Const = function(x) {
const self = getInstance(this, Const)
self[map] = _ => Const(x)
self[extract] = () => x
return Object.freeze(self)
}
const getter = (f, x) => (pipe([
Const,
map(f),
extractFrom
])(x))
console.log(getter(double, 35)) //=> 35此外,通过移除类型检查,一切都是“逻辑上合理的”。
const {create, env} = require('sanctuary');
const {map, pipe, curry} = create({checkTypes: false, env: env});或者用兰达代替避难所。因此,它看起来像是某种类型一致性问题,带有身份映射函数。
问题是我如何让所有这些角色以一种快乐的方式一起发挥。
发布于 2018-06-07 17:29:38
您将需要为您的类型(IdentityType :: Type -> Type)定义一个类型构造函数,并将IdentityType ($.Unknown)包含在您的庇护所环境中,如S.create文档中所述。具体来说,你需要这样的东西:
// IdentityType :: Type -> Type
const IdentityType = $.UnaryType
('my-package/Identity')
('http://example.com/my-package#Identity')
(x => type (x) === Identity['@@type'])
(identity => [Z.extract (identity)]);
const S = create ({
checkTypes: process.env.NODE_ENV !== 'production',
env: env.concat ([IdentityType ($.Unknown)]),
});https://stackoverflow.com/questions/50745797
复制相似问题