1
1
mirror of https://github.com/github/semantic.git synced 2024-12-24 07:25:44 +03:00
semantic/prototype/Doubt/Free.swift

232 lines
9.3 KiB
Swift
Raw Normal View History

2015-10-02 20:54:39 +03:00
/// The free monad over `Syntax`.
///
/// This is free in the sense of unconstrained rather than zero-cost; its the monad obtained by taking a functor (in this case `Syntax`) and adding the minimum necessary details (the `Pure` case) to satisfy the monad laws.
///
2015-10-22 17:12:52 +03:00
/// `Syntax` is a non-recursive type parameterized by the type of its child nodes. Instantiating it to `Free` makes it recursive through the `Roll` case, and allows it to wrap values of type `Value` through the `Pure` case.
2015-10-02 20:54:39 +03:00
///
/// In Doubt, this allows us to represent diffs as values of the `Free` monad obtained from `Syntax`, injecting `Patch` into the tree; or otherwise put, a diff is a tree of mutually-recursive `Free.Roll`/`Syntax` nodes with `Pure` nodes injecting the actual changes.
2015-10-22 17:39:33 +03:00
public enum Free<Leaf, Annotation, Value>: CustomDebugStringConvertible {
2015-10-22 17:12:52 +03:00
/// The injection of a value of type `Value` into the `Syntax` tree.
case Pure(Value)
2015-10-02 21:07:29 +03:00
2015-10-02 21:08:03 +03:00
/// A recursive instantiation of `Syntax`, unrolling another iteration of the recursive type.
indirect case Roll(Annotation, Syntax<Free, Leaf>)
2015-10-02 20:59:55 +03:00
2015-10-07 00:45:24 +03:00
/// Construct a `Free` from a `CofreeType` with matching `Leaf` and `Annotation` types, copying the recursive structure of the term in via hylomorphism.
///
/// The resulting `Free` value will not have any `Pure` cases.
public init<Term: CofreeType where Term.Leaf == Leaf, Term.Annotation == Annotation>(_ term: Term) {
self = hylo(Free.Roll, Term.eliminate)(term)
}
2015-10-28 18:54:40 +03:00
public func analysis<C>(@noescape ifPure ifPure: Value throws -> C, @noescape ifRoll: (Annotation, Syntax<Free, Leaf>) throws -> C) rethrows -> C {
2015-10-02 21:26:53 +03:00
switch self {
case let .Pure(b):
2015-10-28 18:54:40 +03:00
return try ifPure(b)
2015-10-02 21:26:53 +03:00
case let .Roll(s):
2015-10-28 18:54:40 +03:00
return try ifRoll(s)
2015-10-02 21:26:53 +03:00
}
}
2015-10-06 19:47:33 +03:00
/// Reduce the receiver by iteration.
///
/// `Pure` values are simply unpacked. `Roll` values are mapped recursively, and then have `transform` applied to them.
///
2015-10-23 18:36:05 +03:00
/// This forms a _catamorphism_ (from the Greek cata, downwards; compare catastrophe), a generalization of folds over regular trees (and datatypes isomorphic to them). It operates at the leaves first, and then branches near the periphery, recursively collapsing values by whatever is computed by `transform`. Catamorphisms are themselves an example of _recursion schemes_, which characterize specific well-behaved patterns of recursion. This gives `cata` some useful properties for computations performed over trees.
2015-10-06 19:47:33 +03:00
///
2015-10-23 18:36:05 +03:00
/// Due to the character of recursion captured by catamorphisms, `cata` ensures that computation will not only halt, but will further be linear in the size of the receiver. (Nesting a call to `cata` will therefore result in O(n²) complexity.) This guarantee is achieved by careful composition of calls to `map` with recursive calls to `cata`, only calling `transform` once the recursive call has completed. `transform` is itself non-recursive, receiving a `Syntax` whose recurrences have already been flattened to `Value`.
2015-10-06 19:47:33 +03:00
///
2015-10-23 18:36:05 +03:00
/// The linearity of `cata` in the size of the receiver makes it trivial to compute said size, by counting leaves as 1 and summing branches children:
2015-10-06 19:47:33 +03:00
///
2015-10-22 17:37:00 +03:00
/// func size<Leaf, Annotation, Value>(free: Free<Leaf, Annotation, Value>) -> Int {
2015-10-23 18:36:05 +03:00
/// return free.cata { flattenedSyntax in
2015-10-06 19:47:33 +03:00
/// switch flattenedSyntax {
/// case .Leaf:
/// return 1
/// case let .Indexed(children):
/// return children.reduce(0, combine: +)
/// case let .Keyed(children):
/// return children.lazy.map { $1 }.reduce(0, combine: +)
/// }
/// }
/// }
///
2015-10-23 18:36:05 +03:00
/// While not every function on a given `Free` can be computed using `cata`, these guarantees of termination and complexity, as well as the brevity and focus on the operation being performed n times, make it a desirable scaffolding for any function which can.
///
/// For a lucid, in-depth tutorial on recursion schemes, I recommend [Patrick Thomson](https://twitter.com/importantshock)s _[An Introduction to Recursion Schemes](http://patrickthomson.ghost.io/an-introduction-to-recursion-schemes/)_ and _[Recursion Schemes, Part 2: A Mob of Morphisms](http://patrickthomson.ghost.io/recursion-schemes-part-2/)_.
public func cata(@noescape transform: Syntax<Value, Leaf> -> Value) -> Value {
2015-10-06 18:04:14 +03:00
return analysis(
ifPure: id,
ifRoll: { transform($1.map { $0.cata(transform) }) })
2015-10-06 18:04:14 +03:00
}
2015-10-16 01:32:43 +03:00
/// Reduces the receiver top-down, left-to-right, starting from an `initial` value, and applying `combine` to successive values.
public func reduce(initial: Value, @noescape combine: (Value, Value) -> Value) -> Value {
2015-10-23 18:36:05 +03:00
return cata {
switch $0 {
case .Leaf:
return initial
case let .Indexed(a):
return a.reduce(initial, combine: combine)
2015-10-23 21:47:44 +03:00
case let .Fixed(a):
return a.reduce(initial, combine: combine)
case let .Keyed(a):
return a.values.reduce(initial, combine: combine)
}
}
}
2015-10-16 01:13:22 +03:00
/// Returns a function which sums `Free`s by first `transform`ing `Pure` values into integers, and then summing these.
2015-10-22 17:12:52 +03:00
public static func sum(transform: Value -> Int)(_ free: Free) -> Int {
2015-10-16 01:13:22 +03:00
return free.map(transform).reduce(0, combine: +)
}
// MARK: Functor
2015-10-22 17:30:38 +03:00
public func map<C>(@noescape transform: Value -> C) -> Free<Leaf, Annotation, C> {
return analysis(ifPure: { .Pure(transform($0)) }, ifRoll: { .Roll($0, $1.map { $0.map(transform) }) })
2015-10-02 20:59:55 +03:00
}
2015-10-02 21:03:34 +03:00
// MARK: Monad
2015-10-22 17:30:38 +03:00
public func flatMap<C>(@noescape transform: Value -> Free<Leaf, Annotation, C>) -> Free<Leaf, Annotation, C> {
return analysis(ifPure: transform, ifRoll: { .Roll($0, $1.map { $0.flatMap(transform) }) })
2015-10-02 21:03:34 +03:00
}
2015-10-06 23:43:20 +03:00
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
switch self {
case let .Pure(b):
return ".Pure(\(String(reflecting: b)))"
case let .Roll(s):
return ".Roll(\(String(reflecting: s)))"
}
}
2015-10-02 20:43:43 +03:00
}
2015-10-02 21:15:17 +03:00
2015-10-22 19:49:41 +03:00
// MARK: - Anamorphism
extension Free {
public static func Introduce(annotation: Annotation)(syntax: Syntax<Free, Leaf>) -> Free {
return Roll(annotation, syntax)
}
2015-10-22 19:53:18 +03:00
/// Anamorphism over `Free`.
///
/// Unfolds a tree bottom-up by recursively applying `transform` to a series of values starting with `seed`. Since `Syntax.Leaf` does not recur, this will halt when it has produced leaves for every branch.
2015-10-23 18:34:53 +03:00
public static func ana(unfold: Annotation -> Syntax<Annotation, Leaf>)(_ seed: Annotation) -> Free {
return (Introduce(seed) <<< { $0.map(ana(unfold)) } <<< unfold) <| seed
2015-10-22 19:49:41 +03:00
}
}
2015-10-22 17:12:52 +03:00
extension Free where Value: PatchType, Value.Element == Cofree<Leaf, ()> {
public typealias Term = Value.Element
2015-10-22 17:12:52 +03:00
public func merge(transform: Value -> Term) -> Term {
2015-10-23 18:36:05 +03:00
return map(transform).cata { Cofree((), $0) }
2015-10-19 20:05:09 +03:00
}
2015-10-22 17:12:52 +03:00
public func merge(transform: Value -> Term?) -> Term? {
2015-10-23 18:36:05 +03:00
return map(transform).cata(Free.discardNullTerms)
2015-10-19 20:12:45 +03:00
}
2015-10-22 17:10:56 +03:00
private static func discardNullTerms(syntax: Syntax<Term?, Leaf>) -> Term? {
switch syntax {
case let .Leaf(a):
return Cofree((), .Leaf(a))
case let .Indexed(a):
return Cofree((), .Indexed(a.flatMap(id)))
2015-10-23 21:47:44 +03:00
case let .Fixed(a):
return Cofree((), .Fixed(a.flatMap(id)))
case let .Keyed(a):
return Cofree((), .Keyed(Dictionary(elements: a.flatMap { k, v in v.map { (k, $0) } })))
}
}
public var before: Term? {
return merge { $0.state.before }
2015-10-07 04:35:47 +03:00
}
public var after: Term? {
return merge { $0.state.after }
}
}
2015-10-15 18:18:16 +03:00
// MARK: - Patch construction
2015-10-22 17:12:52 +03:00
extension Free where Value: PatchType {
public static func Replace(before: Value.Element, _ after: Value.Element) -> Free {
return .Pure(Value(replacing: before, with: after))
}
2015-10-22 17:12:52 +03:00
public static func Insert(after: Value.Element) -> Free {
return .Pure(Value(inserting: after))
}
2015-10-22 17:12:52 +03:00
public static func Delete(before: Value.Element) -> Free {
return .Pure(Value(deleting: before))
}
2015-10-17 00:44:18 +03:00
public var inverse: Free {
return map { $0.inverse }
}
}
2015-10-02 21:15:17 +03:00
// MARK: - Equality
extension Free {
public static func equals(pure pure: (Value, Value) -> Bool, leaf: (Leaf, Leaf) -> Bool, annotation: (Annotation, Annotation) -> Bool)(_ left: Free, _ right: Free) -> Bool {
2015-10-02 21:15:17 +03:00
switch (left, right) {
case let (.Pure(a), .Pure(b)):
return pure(a, b)
case let (.Roll(annotation1, syntax1), .Roll(annotation2, syntax2)):
return annotation(annotation1, annotation2) && Syntax.equals(leaf: leaf, recur: equals(pure: pure, leaf: leaf, annotation: annotation))(syntax1, syntax2)
2015-10-02 21:15:17 +03:00
default:
return false
}
}
}
2015-10-02 21:18:43 +03:00
public func == <Leaf: Equatable, Value: Equatable, Annotation: Equatable> (left: Free<Leaf, Annotation, Value>, right: Free<Leaf, Annotation, Value>) -> Bool {
return Free.equals(pure: ==, leaf: ==, annotation: ==)(left, right)
}
public func == <Term: CofreeType, Annotation: Equatable where Term.Leaf: Equatable> (left: Free<Term.Leaf, Annotation, Patch<Term>>, right: Free<Term.Leaf, Annotation, Patch<Term>>) -> Bool {
return Free.equals(pure: Patch.equals(Term.equals(==)), leaf: ==, annotation: ==)(left, right)
2015-10-02 21:18:43 +03:00
}
2015-10-02 21:35:07 +03:00
public func == <Term: CofreeType, Annotation where Term.Leaf: Equatable> (left: Free<Term.Leaf, Annotation, Patch<Term>>, right: Free<Term.Leaf, Annotation, Patch<Term>>) -> Bool {
return Free.equals(pure: Patch.equals(Term.equals(==)), leaf: ==, annotation: const(true))(left, right)
2015-10-14 23:32:01 +03:00
}
2015-10-02 21:35:07 +03:00
2015-10-09 15:39:57 +03:00
// MARK: - JSON
2015-10-08 14:21:08 +03:00
extension Free {
public func JSON(pure pure: Value -> Doubt.JSON, leaf: Leaf -> Doubt.JSON, annotation: Annotation -> Doubt.JSON) -> Doubt.JSON {
2015-10-08 14:30:02 +03:00
return analysis(
ifPure: { [ "pure": pure($0) ] },
2015-10-08 14:30:34 +03:00
ifRoll: {
[ "roll": [
"extract": annotation($0),
"unwrap": $1.JSON(leaf: leaf, recur: { $0.JSON(pure: pure, leaf: leaf, annotation: annotation) })
] ]
2015-10-08 14:30:34 +03:00
})
2015-10-08 14:21:08 +03:00
}
}
2015-10-13 07:55:20 +03:00
import Prelude