1
1
mirror of https://github.com/github/semantic.git synced 2024-11-29 02:44:36 +03:00
semantic/prototype/Doubt/TermType.swift

47 lines
1.0 KiB
Swift
Raw Normal View History

2015-10-14 20:52:25 +03:00
/// The type of terms.
public protocol TermType {
typealias LeafType
var unwrap: Syntax<Self, LeafType> { get }
2015-10-14 20:52:25 +03:00
}
2015-10-14 20:57:21 +03:00
2015-10-15 01:42:20 +03:00
extension TermType {
2015-10-15 04:07:30 +03:00
/// Catamorphism over `TermType`s.
///
/// Folds the tree encoded by the receiver into a single value by recurring top-down through the tree, applying `transform` to leaves, then to branches, and so forth.
2015-10-15 01:42:20 +03:00
public func cata<Result>(transform: Syntax<Result, LeafType> -> Result) -> Result {
return self |> ({ $0.unwrap } >>> { $0.map { $0.cata(transform) } } >>> transform)
2015-10-15 01:42:20 +03:00
}
2015-10-15 01:47:20 +03:00
/// The size of the receiver.
public var size: Int {
return cata {
switch $0 {
case .Leaf:
return 1
case let .Indexed(i):
return i.reduce(1, combine: +)
case let .Keyed(k):
return k.values.reduce(1, combine: +)
}
}
}
2015-10-15 01:42:20 +03:00
}
extension Cofree: TermType {}
2015-10-14 21:05:43 +03:00
// MARK: - Equality
extension TermType {
public static func equals(leaf: (LeafType, LeafType) -> Bool)(_ a: Self, _ b: Self) -> Bool {
return Syntax.equals(ifLeaf: leaf, ifRecur: equals(leaf))(a.unwrap, b.unwrap)
2015-10-14 21:05:43 +03:00
}
}
2015-10-15 01:42:20 +03:00
import Prelude