Last active
February 3, 2020 13:33
-
-
Save lupuszr/92c8322636dedad71d0adab5f7d2a444 to your computer and use it in GitHub Desktop.
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
// Universal constructions based on Bartosz Milewski talk on Scala World | |
// type ProductT<C, A, B> = | |
function fanout<C, A, B>(f: (c: C) => A, g: (c: C) => B): ((c: C) => [A, B]) { | |
return c => [f(c), g(c)] | |
} | |
// const x = fanout((a: number) => a + 1, b => b + 2)(4) | |
function compose2<U, A, D>(a: (u: U) => A,b: (a: A) => D) { | |
return (u: U) => b(a(u)) | |
} | |
function _1<A, B>(h: [A, B]): A { | |
return h[0]; | |
} | |
function _2<A, B>(h: [A, B]): B { | |
return h[1]; | |
} | |
function fanin<C, A, B>(h: (c: C) => [A, B]): [(c: C) => A, (c: C) => B] { | |
return [ | |
//(cz: C) => _1(h(cz)), | |
compose2(h, _1), | |
// (cz: C) => _2(h(cz)) | |
compose2(h, _2) | |
] | |
} | |
// functoriality of a product | |
// f: A -> A' | |
// g: B -> B' | |
// (A, B) -> (A', B') | |
function bimap<A, B, A1, B1>( | |
p: [A, B], | |
f: (a: A) => A1, | |
g: (b: B) => B1): [A1, B1] { | |
// return [ | |
// f(_1(p)), | |
// g(_2(p)) | |
// ] | |
const f1 = compose2<[A,B], A, A1>(_1, f); | |
const g1 = compose2<[A,B], B, B1>(_2, g); | |
return fanout( | |
f1, | |
g1, | |
)(p) | |
} | |
// const r = bimap( | |
// [10, "hello"], | |
// a => a * 20, | |
// b => b.repeat(3) | |
// ) | |
/// SUM | |
class Either<A, B> { | |
a: A; | |
b: B; | |
constructor(a: A, b: B) { | |
this.a = a; | |
this.b = b; | |
} | |
static Left<A, B>(a: A) { | |
const b = undefined as unknown as B; | |
return new Either<A, B>(a, b); | |
} | |
static Right<A, B>(b: B) { | |
const a = undefined as unknown as A; | |
return new Either<A, B>(a, b); | |
} | |
} | |
function exist<A>(a: A) { | |
if (a) return true; | |
return false; | |
} | |
function either<A, B, C>(f: (a: A) => C, g: (b: B) => C): ((e: Either<A, B>) => C) { | |
return (e: Either<A, B>) => { | |
switch(true) { | |
case exist(e.a): return f(e.a); | |
case exist(e.b): return g(e.b); | |
} | |
return f(e.a); | |
} | |
} | |
// const x = Either.left(10); | |
// const z = either((a: number) => a + 100, b => 0)(x) | |
function foo<C, A, B>(h: (a: Either<A,B>) => C): [(a: A) => C, (b: B) => C] { | |
return [ | |
a => h(Either.Left(a)), | |
b => h(Either.Right(b)) | |
] | |
} |
Hello @stjordanis, this code was in fact based on a talk from Bartosz Milewski and John De Goes was doing live coding in scala. So if you are interested in scala implementation you can see it here https://www.youtube.com/watch?v=UjSQlUjuZWQ. I am quite sure that there is a repo with it as well somewhere.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, could you please code the equivalent scala code, too?