Created
July 23, 2020 07:46
-
-
Save abiodun0/d0b474a2c34e4104b8a8f261dd70b348 to your computer and use it in GitHub Desktop.
commonads, monoids and trees
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
// Leaf : val -> ann -> Tree val ann | |
function Leaf(val, ann) { | |
return { | |
ann: ann, | |
val: val, | |
toString: () => `Leaf(${val}, ${ann})`, | |
map: f => Leaf(val, f(ann)), | |
extend: f => Leaf(val, f(Leaf(val, ann))), | |
reduce: (f, acc) => f(acc, ann), | |
}; | |
} | |
// Branch : Tree val ann -> Tree val ann -> ann -> Tree val ann | |
function Branch(left, right, ann) { | |
return { | |
ann: ann, | |
left: left, | |
right: right, | |
toString: () => `Branch(${left}, ${right}, ${ann})`, | |
map: f => Branch(left.map(f), right.map(f), f(ann)), | |
extend: f => | |
Branch(left.extend(f), right.extend(f), f(Branch(left, right, ann))), | |
reduce: (f, acc) => right.reduce(f, left.reduce(f, f(acc, ann))), | |
}; | |
} | |
// Any : Bool -> Any | |
function Any(bool) { | |
return { | |
bool: bool, | |
concat: a => Any(bool || a.bool), | |
}; | |
} | |
Any.empty = () => Any(false); | |
// foldMap : (Monoid m, Foldable f) => m -> (a -> m) -> f a -> m | |
const foldMap = (Monoid, f, Foldable) => | |
Foldable.reduce((acc, x) => acc.concat(f(x)), Monoid.empty()) | |
// fold : (Monoid m, Foldable f) => m -> f m -> m | |
const fold = (Monoid, Foldable) => foldMap(Monoid, x => x, Foldable)); | |
// changed : Tree val Bool -> Bool | |
const changed = tree => foldMap(Any, Any, tree).bool; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment