Last active
December 10, 2017 05:30
-
-
Save calam1/d924dfa3dd71e06a3f096e596bdd2667 to your computer and use it in GitHub Desktop.
contravariant functor in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://medium.com/@drboolean/monoidal-contravariant-functors-are-actually-useful-1032211045c4 | |
const log = require('./lib/log') | |
log( | |
'testing' | |
) | |
const daggy = require('daggy') | |
const { | |
foldMap | |
} = require('pointfree-fantasy') | |
const { | |
concat, | |
toUpper, | |
prop, | |
identity, | |
range, | |
compose | |
} = require('ramda') | |
const Comparison = daggy.tagged('Comparison', ['f']) | |
const GT = 1 | |
const LT = -1 | |
const EQ = 0 | |
const concatOrd = (o1, o2) => (o1 === EQ) ? o2 : o1 | |
const emptyOrd = EQ | |
Comparison.prototype.concat = function (c) { | |
return Comparison((x, y) => concatOrd(this.f(x, y), c.f(x, y))) | |
} | |
Comparison.empty = () => Comparison((x, y) => EQ) | |
Comparison.prototype.empty = Comparison.empty | |
Comparison.prototype.contramap = function (g) { | |
return Comparison((x, y) => this.f(g(x), g(y))) | |
} | |
const eq21 = (a, b) => { | |
if (a === 21) { | |
return GT | |
} | |
if (b === 21) { | |
return LT | |
} | |
return EQ | |
} | |
const over21 = (a, b) => { | |
if (a > 21) { | |
return LT | |
} | |
if (b > 21) { | |
return GT | |
} | |
return EQ | |
} | |
const greater = (a, b) => { | |
if (a > b) { | |
return GT | |
} | |
if (b > a) { | |
return LT | |
} | |
return EQ | |
} | |
const blackjack = foldMap(Comparison, [eq21, over21, greater]) | |
const cardToInt = prop('val') | |
const cards = [{ | |
suit: 'hearts', | |
val: 8 | |
}, { | |
suit: 'diamonds', | |
val: 4 | |
}, { | |
suit: 'clubs', | |
val: 7 | |
}] | |
log( | |
cards.sort(blackjack.contramap(cardToInt).f) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment