1
1
mirror of https://github.com/github/semantic.git synced 2024-12-28 09:21:35 +03:00

Add a Keyed case to Syntax.

This commit is contained in:
Rob Rix 2015-10-02 17:18:38 -04:00
parent 6657c5c0a5
commit 20bea59868

View File

@ -33,6 +33,7 @@ public func == <A: Equatable> (left: Term<A>, right: Term<A>) -> Bool {
public enum Syntax<Recur, A>: CustomDebugStringConvertible, CustomDocConvertible {
case Leaf(A)
case Indexed([Recur])
case Keyed([String:Recur])
public func map<T>(@noescape transform: Recur -> T) -> Syntax<T, A> {
switch self {
@ -40,6 +41,8 @@ public enum Syntax<Recur, A>: CustomDebugStringConvertible, CustomDocConvertible
return .Leaf(n)
case let .Indexed(x):
return .Indexed(x.map(transform))
case let .Keyed(d):
return .Keyed(Dictionary(elements: d.map { ($0, transform($1)) }))
}
}
@ -49,6 +52,9 @@ public enum Syntax<Recur, A>: CustomDebugStringConvertible, CustomDocConvertible
case let .Indexed(x):
return try x.reduce(initial, combine: combine)
case let .Keyed(d):
return try d.lazy.map { $1 }.reduce(initial, combine: combine)
default:
return initial
}
@ -60,6 +66,8 @@ public enum Syntax<Recur, A>: CustomDebugStringConvertible, CustomDocConvertible
return ".Leaf(\(n))"
case let .Indexed(x):
return ".Indexed(\(String(reflecting: x)))"
case let .Keyed(d):
return ".Keyed(\(String(reflecting: d)))"
}
}
@ -69,6 +77,8 @@ public enum Syntax<Recur, A>: CustomDebugStringConvertible, CustomDocConvertible
return Doc(n)
case let .Indexed(x):
return x.map(Doc.init).joinWithSeparator(", ").bracket("[", "]")
case let .Keyed(d):
return d.lazy.map { Doc($0) <> Doc(":") <+> Doc($1) }.joinWithSeparator(", ").bracket("[", "]")
}
}
}
@ -83,6 +93,8 @@ extension Syntax {
return ifLeaf(l1, l2)
case let (.Indexed(v1), .Indexed(v2)):
return v1.count == v2.count && zip(v1, v2).lazy.map(ifRecur).reduce(true) { $0 && $1 }
case let (.Keyed(d1), .Keyed(d2)):
return Array(d1.keys) == Array(d2.keys) && d1.keys.lazy.map { ifRecur(d1[$0]!, d2[$0]!) }.reduce(true) { $0 && $1 }
default:
return false
}
@ -107,6 +119,8 @@ extension Syntax {
return Hash("Leaf", ifLeaf(n))
case let .Indexed(x):
return Hash("Indexed", .Ordered(x.map(ifRecur)))
case let .Keyed(d):
return Hash("Keyed", .Ordered(d.keys.sort().map { Hash($0, ifRecur(d[$0]!)) }))
}
}
}