Sanctuary Js and Defining a Contravariant Functor

398 views Asked by At

I am trying this from scratch learning about Contravariants and deeper knowledge of Sanctuary. The code "works" but again I don't have the types exactly right.

Here is the Contravariant

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'

And my attempt to get the types right

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)

Then my test

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.

If I disable the type checking then it works as expected, so logically it appears to be stitched together properly. I defined my own version of 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
        }
    )

I then rerun the test:

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

So withstanding the discussion as to whether the contravaiant functor is the best approach to this problem (learning exercise), the question is how, when defining my own implementation of a contravariant, can I use sanctuary's contramap function with the type checking enabled.


after updating by adding the code:

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

changed the error to:

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]

My understanding of the contravariant functor was that it pre-composed the function within it, with the function passed in via contramap. So if the contravariant contained the function f and it is contramap with g it returns a new contravariant functor wrapping x = g(f(x)) Have i misunderstood this (too)

2

There are 2 answers

6
davidchambers On

You're composing functions. Sanctuary defines fantasy-land/map and fantasy-land/contramap for Function a b, so there's no need for a Contra wrapping type.

> S.map (S.even) (s => s.length) ('Sanctuary')
false

> S.contramap (s => s.length) (S.even) ('Sanctuary')
false
0
davidchambers On

Here's the boilerplate for defining a custom type and including it in the Sanctuary environment:

'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