// Copyright © 2015 GitHub. All rights reserved. /// The cofree comonad over `Syntax`. /// /// This is “free” in the sense of “unconstrained” rather than “zero-cost”; it’s the comonad obtained by taking a functor (in this case `Syntax`) and adding the minimum necessary details (the `B` paired with it) to satisfy the comonad laws. /// /// This type is dual to `Free`. Where `Free` is inhabited by syntax trees where some terms are replaced with `B`s, `Cofree` is inhabited by syntax trees where all terms are annotated with `B`s. In Doubt, this allows us to e.g. annotate terms with source range information, categorization, etc. public enum Cofree { indirect case Unroll(B, Syntax) public var unwrap: Syntax { switch self { case let .Unroll(_, rest): return rest } } /// Recursively copies a `Fix` into a `Cofree` with a function assigning `B` for every `Fix`. public init(_ fix: Fix, _ annotate: Fix -> B) { self = Cofree>.coiterate { $0.out } (fix).map(annotate) } /// Constructs a cofree by coiteration. /// /// The initial seed is used as the annotation of the returned value. The continuation of the structure is unpacked by applying `annotate` to the seed and mapping the resulting syntax’s values recursively. In this manner, the structure is unfolded bottom-up, starting with `seed` and ending at the leaves. /// /// As this is the dual of `Free.iterate`, it’s unsurprising that we have a similar guarantee: coiteration is linear in the size of the constructed tree. public static func coiterate(annotate: B -> Syntax)(_ seed: B) -> Cofree { return .Unroll(seed, annotate(seed).map(coiterate(annotate))) } } // MARK: - Functor extension Cofree { public func map(@noescape transform: B -> Other) -> Cofree { return .Unroll(transform(extract), unwrap.map { $0.map(transform) }) } } // MARK: - Comonad extension Cofree { /// Returns the value annotating the syntax tree at this node. public var extract: B { switch self { case let .Unroll(b, _): return b } } /// Returns a new `Cofree` by recursively applying `transform` to each node, producing the annotations for the copy. public func extend(@noescape transform: Cofree -> Other) -> Cofree { return .Unroll(transform(self), unwrap.map { $0.extend(transform) }) } /// Returns a new `Cofree` constructed by recursively annotating each subtree with itself. public var duplicate: Cofree> { return extend(id) } } import Prelude