Merge each entry of a list nested inside a tuple with the other part of the tuple

115 views Asked by At

I have a list (let's call it L1) of tuples, in this tuple _1 is some class with data and _2 is a list (let's call it L2) of some other classes with other data. For each entry of L1 (that is a list of tuples) I need to merge each entry of L2 with the corresponding _1. I am trying to compose a lens, but getting stuck. Here's a code snippet to demonstrate what I'm trying to achieve:

  case class LiveData(information: String)
  case class StoredData(uniqueId: String)
  case class MergedData(uniqueId: String, information: String)

  def merge(live: LiveData, stored: StoredData): MergedData = MergedData(stored.uniqueId, live.information)
  
  type Data = (LiveData, List[StoredData])
  type UpdatedData = (LiveData, List[MergedData])
  
  def process(dataEntries: List[Data]): List[UpdatedData] = {
    val stored = GenLens[Data](_._2).each
    val live = GenLens[Data](_._1)
    val composed = ???
    ???
  }

What I'd like to be able to do is something like this:

def process(dataEntries: List[Data]): List[UpdatedData] = {
  val someLens = ???  
  someLens.each.modify(merge)(dataEntries)
}

Am I going in the right direction? Should I somehow try to compose these two lenses or do I need something completely different? I also use Cats in my project, but I'm very new to that and can't see at this time if it could be of any use in this situation.

1

There are 1 answers

1
jwvh On

This type-checks and compiles.

def merge(dataEntries: List[Data]): List[UpdatedData] =
  dataEntries.map{ 
    case (ld, sds) =>
      (ld, sds.map(sd => MergedData(sd.uniqueId, ld.information)))
  }

If this isn't what you're looking for then perhaps you could be a bit more specific.