Skip to content

Instantly share code, notes, and snippets.

@moust
Created September 6, 2022 15:03
Show Gist options
  • Save moust/7f6f17cf766a5892f9795812814d8fbc to your computer and use it in GitHub Desktop.
Save moust/7f6f17cf766a5892f9795812814d8fbc to your computer and use it in GitHub Desktop.
import shapeless.{HList, LabelledGeneric, Poly1, Witness}
import shapeless.labelled.{FieldType, field}
import shapeless.ops.hlist
import shapeless.tag.@@
trait Primary {
val primary: Option[Boolean]
}
object OnlyOnePrimary {
sealed trait LowerPriorityFieldMapper extends Poly1 {
implicit def c[K, V]: Case.Aux[FieldType[K, V], FieldType[K, V]] =
at[FieldType[K, V]](identity)
}
object unflagPrimary extends LowerPriorityFieldMapper {
type PrimaryKey = Symbol @@ Witness.`"primary"`.T
implicit val primary: Case.Aux[FieldType[PrimaryKey, Option[Boolean]], FieldType[PrimaryKey, Option[Boolean]]] =
at[FieldType[PrimaryKey, Option[Boolean]]] { _ =>
field[PrimaryKey](Some(false))
}
}
def apply[A <: Primary, Repr <: HList](
list: List[A]
)(implicit generic: LabelledGeneric.Aux[A, Repr],
mapper: hlist.Mapper.Aux[unflagPrimary.type, Repr, Repr],
): List[A] =
list match {
case Nil => Nil
case head :: tail if head.primary.exists(identity) =>
head :: tail.map { elem =>
generic.from(generic.to(elem).map(unflagPrimary))
}
case head :: tail => head :: apply(tail)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment