Last active
March 27, 2018 20:54
-
-
Save DrBoolean/1ffd18761098be72a3dd6ec4603d811b to your computer and use it in GitHub Desktop.
Either and Tuple (the canonical Sum/Product types, respectively) used to make a List
This file contains hidden or 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
const {Left, Right} = require('data.either') | |
const Tuple = require('fantasy-tuples').Tuple2 | |
//List :: Either Null (Tuple a List) | |
const empty = () => | |
Left(null) | |
const cons = (x, l) => | |
Right(Tuple(x, l)) | |
const map = (f, l) => | |
l.cata({ | |
Right: t => cons(f(t._1), map(f, t._2)), | |
Left: e => empty() | |
}) | |
const reduce = (f, z, l) => | |
l.cata({ | |
Right: t => reduce(f, f(z, t._1), t._2), | |
Left: e => z | |
}) | |
const toArray = l => | |
reduce((acc, x) => [x].concat(acc), [], l) | |
const fromArray = xs => | |
xs.reduce((acc, x) => cons(x, acc), empty()) | |
const l = fromArray([1, 2, 3]) // || cons(3, cons(2, cons(1, empty()))) | |
toArray(l) | |
// [ 1, 2, 3 ] | |
toArray(cons(4, l)) | |
// [ 1, 2, 3, 4 ] | |
toArray(map(x => x + 1, l)) | |
// [ 2, 3, 4 ] | |
reduce((acc, x) => acc + x, 0, l) | |
// 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment