我正在学习 YouTube 上的 Bartosz Milewski 范畴理论课程。他将 Const 和 Identity 函子描述为可以派生的“基础”函子(可能是我的自由解释)。
一旦我开始与地图和管道的 Sanctuary 库集成,我的问题就出现了,已经实现了 ES6+ / Fantasy-land(不重要)版本的函子。
实现非常简单
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: 70
TypeError: Type-variable constraint violation map :: Functor f => (a -> b) -> f a -> f b ^ ^ 1 2 1) 35 :: Number, FiniteNumber, NonZeroFiniteNumber, Integer, NonNegativeInteger, ValidNumber 2) () => x :: Function, (c -> d) f => Identity(f(x)) :: Function, (c -> d) Since there is no type of which all the above values are members, the type-variable constraint has been violated.
但是 Const 仿函数工作得更好一些(地图中没有调用 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});
或用 ramda 替换 sanctuary。所以它看起来像是身份映射函数的某种类型一致性问题。
问题是我如何让所有这些部分以一种快乐的方式一起玩。