Skip to content

Commit

Permalink
Convert FactTable to a universal trait
Browse files Browse the repository at this point in the history
- Add SimpleFactTable as a simple implementation
  • Loading branch information
Jeff May authored and jeffmay committed Aug 31, 2022
1 parent a66c35a commit 6078e07
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions core-v1/src/main/scala/data/FactTable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@ import scala.collection.immutable.SortedMap
*
* @note some expressions can update the fact table for sub-expressions.
*/
final case class FactTable(factsByName: SortedMap[String, FactSet]) extends AnyVal {
trait FactTable extends Any {
protected type Self <: FactTable

protected def build(factsByName: SortedMap[String, FactSet]): Self

protected def factsByName: SortedMap[String, FactSet]

def add(fact: Fact): FactTable = addAll(FactSet(fact))

def addAll(facts: Iterable[Fact]): FactTable = {
def addAll(facts: Iterable[Fact]): Self = {
import cats.syntax.semigroup._
val newFactTable = FactTable.fromSet(facts.toSet)
new FactTable(this.factsByName |+| newFactTable.factsByName)
build(this.factsByName |+| newFactTable.factsByName)
}

def getSortedSeq[T](factTypeSet: FactTypeSet[T]): IndexedSeq[TypedFact[T]] = {
Expand Down Expand Up @@ -51,7 +56,7 @@ final case class FactTable(factsByName: SortedMap[String, FactSet]) extends AnyV

object FactTable {

final val empty = new FactTable(SortedMap.empty)
final val empty = SimpleFactTable(SortedMap.empty)

def apply(facts: FactOrFactSet*): FactTable = {
val factSet = FactOrFactSet.flatten(facts)
Expand All @@ -60,7 +65,7 @@ object FactTable {

def fromSet(factSet: FactSet): FactTable = {
if (factSet.isEmpty) empty
else new FactTable(SortedMap.from(factSet.groupBy(_.typeInfo.nameAndFullType)))
else SimpleFactTable(SortedMap.from(factSet.groupBy(_.typeInfo.nameAndFullType)))
}

implicit object MonoidInstance extends Monoid[FactTable] {
Expand All @@ -70,7 +75,7 @@ object FactTable {
y: FactTable,
): FactTable = {
import cats.syntax.semigroup._
new FactTable(x.factsByName |+| y.factsByName)
SimpleFactTable(x.factsByName |+| y.factsByName)
}
}

Expand All @@ -90,3 +95,11 @@ object FactTable {
}
}
}

/**
* A simple value class wrapper around a Map of Strings to [[FactSet]]s.
*/
final case class SimpleFactTable(factsByName: SortedMap[String, FactSet]) extends AnyVal with FactTable {
override protected type Self = SimpleFactTable
override protected def build(factsByName: SortedMap[String, FactSet]): SimpleFactTable = SimpleFactTable(factsByName)
}

0 comments on commit 6078e07

Please sign in to comment.