2

I want to merge an update instance of a class into a base instance, choosing the field of the update instance over the base instance if that field is "empty" in the base instance. The example below merges base and update:

case class Foo(a: Option[Int], b: List[Int], c: Option[Int])

val base = Foo(None, Nil, Some(0))
val update = Foo(Some(3), List(4), None)

merge(base,update) == Foo(Some(3), List(4), Some(0))

I've tried something like this:

val g = Generic[Foo]
val aHList = g.to(base)
val bHList = g.to(update)

aHList
  .zipWithIndex
  .map({
    case (l: List, i: Int) => l ++ bHList(i)
    case (o: Option, i: Int) => if (!bHList(i).nonEmpty) {
      updateHList(i)
    } else {
      o
    }
    case (_, i: Int) => updateHList(i)
  })

But it turns out the generic .to method does not output an HList per say but a Repr. Any idea how I could achieve my goal?

Thank you !

2 Answers 2

6

For specific tasks like this, it is most often easier to create a type class than to dabble with something like a map with a Poly.

We can represent an update on some T as follows :

trait Update[T] {
  def apply(base: T, update: T): T
}

Now we need to define some instances. How to update a List and Option and some instances to make it possible to derive an Update[Foo] instance.

import shapeless._

object Update extends Update0 {
  def apply[A](implicit update: Lazy[Update[A]]): Update[A] = update.value

  implicit def optionUpdate[A]: Update[Option[A]] = 
    new Update[Option[A]] {
      def apply(base: Option[A], update: Option[A]): Option[A] = update orElse base
    }

  implicit def listUpdate[A]: Update[List[A]] = 
    new Update[List[A]] {
      def apply(base: List[A], update: List[A]): List[A] = base ++ update
    }

  implicit def hnilUpdate: Update[HNil] = 
    new Update[HNil] {
      def apply(base: HNil, update: HNil): HNil = HNil
    }

  implicit def hconsUpdate[H, T <: HList](
    implicit updateH: Update[H], updateT: Lazy[Update[T]]
  ): Update[H :: T] = 
    new Update[H :: T] {
      def apply(base: H :: T, update: H :: T): H :: T = 
        updateH(base.head, update.head) :: updateT.value(base.tail, update.tail)
    }
}

trait Update0 {
  implicit def genericUpdate[A, G <: HList](
    implicit gen: Generic.Aux[A, G], updateG: Lazy[Update[G]]
  ): Update[A] =
    new Update[A] {
      def apply(base: A, update: A): A = 
        gen.from(updateG.value(gen.to(base), gen.to(update)))
    }
}

We can add some syntax to make it a little bit easier :

implicit class UpdateOps[A](val base: A) extends AnyVal {
  def update(change: A)(implicit update: Lazy[Update[A]]): A = 
    update.value(base, change)
}

Now we can do :

case class Foo(a: Option[Int], b: List[Int], c: Option[Int])

val base = Foo(None, Nil, Some(0))
val update = Foo(Some(3), List(4), None)

base update update // Foo(Some(3),List(4),Some(0))

We could define an instance for cats.SemigroupK or scalaz.Plus so we could omit the Option and List instances, while gaining eg Update[Vector[Int]] :

import cats.SemigroupK
import cats.implicits._

implicit def semigroupKUpdate[F[_], A](implicit F: SemigroupK[F]): Update[F[A]] =
  new Update[F[A]] {
    def apply(base: F[A], update: F[A]): F[A] = F.combineK(update, base)
  }
4
  • Nice solution, thx ! Why are putting genericUpdate in a different trait ? Why not have it in Update ? Jun 23, 2016 at 15:09
  • Like it is, it should be fine in Update. But if for example you want to create a custom Update[(A, B)], the genericUpdate needs to be in a trait because otherwise you would get ambiguous implicits. Jun 23, 2016 at 15:25
  • As for the setup I have a compile error, it can't find the Update[Foo] implicit. I have the Update trait and object in a file. And the UpdateOps[A] in a package object. I import both the package object as well the content of the Update object. Looks like it does not find the GenericUpdate. On another note, what is G for in the genericUpdate ? Jun 23, 2016 at 15:36
  • My bad, forgot to add implicits for other datatypes. The error mislead me. Jun 23, 2016 at 18:57
2

You can use Poly and map to solve this problem in a very general way. I think the solution is quite elegant.

import shapeless._
import shapeless.ops.hlist._
import syntax.std.tuple._

trait LowPriority extends Poly1 {
  implicit def default[T, U] = at[(T, U)]{ case (t, u) => t }
}

object ChooseNonEmpty extends LowPriority {
  type OverNone[A] = (None.type, A)
  type OverNil[A] = (Nil.type, A)
  implicit def caseNone[T] = at[OverNone[T]] { case (t, u) => u }
  implicit def caseList[T] = at[OverNil[T]] { case (t, u) => u }
}

object test {
  def merge[C, HF <: Poly, Repr <: HList, ZRepr <: HList, MRepr <: HList](f:HF)(base:C, update:C)
  (implicit
       gen:Generic.Aux[C, Repr],
       zipper:Zip.Aux[Repr :: Repr :: HNil, ZRepr],
       mapper:Mapper.Aux[f.type, ZRepr, MRepr]): C = {

    val basep = gen.to(base)
    val updatep = gen.to(update)

    val zipped = basep zip updatep

    gen.from( (zipped map f).asInstanceOf[Repr])
  }
}

Edit: figured out how to match None and Nil object types embedded in Tuples with a Poly. Added it and simplified the code.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.