From 822ce7ccc509cd845501b6d06d023ec9fa03bedb Mon Sep 17 00:00:00 2001 From: Rob Rix Date: Thu, 12 Nov 2015 17:44:35 -0500 Subject: [PATCH] Add a `Cofree.size` function. This should avoid the protocol indirection around `TermType`. --- prototype/Doubt/Cofree.swift | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/prototype/Doubt/Cofree.swift b/prototype/Doubt/Cofree.swift index a0bfe3c0f..a5c897c20 100644 --- a/prototype/Doubt/Cofree.swift +++ b/prototype/Doubt/Cofree.swift @@ -201,4 +201,25 @@ extension Cofree { } +// MARK: - Size + +extension Cofree { + /// The count of nodes in the receiver. + /// + /// This is used to compute the cost of patches, such that a patch inserting a very large tree will be charged approximately the same as a very large tree consisting of many small patches. + public static func size(term: Cofree) -> Int { + switch term.unwrap { + case .Leaf: + return 1 + case let .Indexed(a): + return a.reduce(0) { $0 + size($1) } + case let .Fixed(a): + return a.reduce(0) { $0 + size($1) } + case let .Keyed(a): + return a.reduce(0) { $0 + size($1.1) } + } + } +} + + import Prelude