首页 > 解决方案 > Sanctuary Js 和定义逆变函子

问题描述

我正在尝试从头开始学习逆变器和对 Sanctuary 的更深入了解。代码“有效”,但我再次没有完全正确的类型。

这是逆变式

const {contramap: contramapFl, extract } = require('fantasy-land');
const getInstance = (self, constructor) =>
    (self instanceof constructor) ?
        self :
        Object.create(constructor.prototype) ;
// Contra a ~> g: a -> ?
const Contra = function(g){
    const self = getInstance(this, Contra)

    // :: F a ~> b -> a -> F b [ b -> a -> ? ]
    self[contramapFl] = f => Contra( x => g(f(x)) )
    self[extract] = g
    self['@@type'] =  'fs-javascript/contra'

    return Object.freeze(self)
}
// UPDATE adding type to constructor
Contra['@@type'] =  'fs-javascript/contra'

我试图让类型正确

const $ = require('sanctuary-def');
const type = require('sanctuary-type-identifiers');
const Z = require('sanctuary-type-classes') ;

const isContra = x => type (x) === 'fs-javascript/contra'

const ContraType = $.UnaryType(
    'fs-javascript/contra',
    'http://example.com/fs-javascript#Contra',
    isContra,
    x => [x[extract]])($.Unknown)

然后我的测试

const {create, env} = require('sanctuary');
const {contramap} = create({checkTypes: true, env: env.concat(ContraType) });

const isEven = Contra(x => x % 2 === 0) ;
console.log(Z.Contravariant.test(isEven)) // => true

const isLengthEvenContra = contramap(y => y.length, isEven)
const isStringLengthEven = isLengthEvenContra[extract]

console.log(isStringLengthEven("asw")) //=> ERROR
TypeError: Type-variable constraint violation

contramap :: Contravariant f => (b -> a) -> f a -> f b
                                              ^
                                              1

1)  "fs-javascript/contra" :: String
    f => Contra( x => g(f(x)) ) :: Function, (c -> d)
    x => x % 2 === 0 :: Function, (c -> d)

Since there is no type of which all the above values are members, the type-variable constraint has been violated.

如果我禁用类型检查,那么它会按预期工作,所以从逻辑上讲,它似乎被正确地缝合在一起。我定义了我自己的 contramap 版本

const def = $.create({ checkTypes: true, env: $.env.concat(ContraType) });

const contramap2 =
    def('contramap2', {}, [$.Unknown, ContraType, ContraType],
        (f, x) => {
            const z = x[contramapFl](f)
            return z
        }
    )

然后我重新运行测试:

const isEven = Contra(x => x % 2 === 0) ;
console.log(Z.Contravariant.test(isEven)) // => true

const isLengthEvenContra = contramap2(y => y.length, isEven)
const isStringLengthEven = isLengthEvenContra[extract]

console.log(isStringLengthEven("asw")) //=> false

因此,尽管讨论了逆变函子是否是解决这个问题的最佳方法(学习练习),但问题是,在定义我自己的逆变函数实现时,我如何可以在启用类型检查的情况下使用 sanctuary 的 contramap 函数


通过添加代码更新后:

Contra['@@type'] =  'fs-javascript/contra'

将错误更改为:

TypeError: Type-variable constraint violation

contramap :: Contravariant f => (b -> a) -> f a -> f b
                                      ^       ^
                                      1       2

1)  3 :: Number, FiniteNumber, NonZeroFiniteNumber, Integer, NonNegativeInteger, ValidNumber

2)  x => x % 2 === 0 :: Function, (c -> d)

Since there is no type of which all the above values are members, the type-variable constraint has been violated.
// Contra (Integer -> Boolean)
const isEven = Contra(x => x % 2 === 0) ;
// String -> Integer
const strLength = y => y.length
// I Think: Contra (String -> (Integer -> Boolean))
const isLengthEvenContra = contramap(strLength, isEven)
// (String -> (Integer -> Boolean))
const isStringLengthEven = isLengthEvenContra[extract]

我对逆变函子的理解是,它在其中预先组合了函数,函数通过 via 传入contramap。所以如果逆变包含函数f并且它contramapg它一起返回一个新的逆变函子包装x = g(f(x)) 我是否误解了这个(太)

标签: javascriptfunctional-programmingfantasylandsanctuary

解决方案


这是定义自定义类型并将其包含在 Sanctuary 环境中的样板:

'use strict';

const {create, env} = require ('sanctuary');
const $             = require ('sanctuary-def');
const type          = require ('sanctuary-type-identifiers');

//    FooType :: Type -> Type
const FooType = $.UnaryType
  ('my-package/Foo')
  ('https://my-package.org/Foo')
  (x => type (x) === 'my-package/Foo@1')
  (foo => []);

//    foo :: Foo
const foo = {
  'constructor': {'@@type': 'my-package/Foo@1'},
  'fantasy-land/contramap': function(f) {
    throw new Error ('Not implemented');
  },
};

const S = create ({
  checkTypes: true,
  env: env.concat ([FooType ($.Unknown)]),
});

S.I (foo);
// => foo

S.contramap (S.I) (foo);
// ! Error: Not implemented

推荐阅读