Toren
Toren

Reputation: 6856

Find common items in two lists (Scala)

A newbie Scala question .

I'm trying to implement a function that receive two Lists ,find a common item , than make manipulation and create a new list

I have a case class

case class weightedFruits(fruits: Set[String], weight: Double) 

and two lists weightedFruitsList and filteredWeightedFruitsList:

// set is sorted 
val weightedFruitsList = List(
weightedFruits(Set("banana"), 200),
weightedFruits(Set("banana", "orange"), 180),
weightedFruits(Set("banana", "orange", "apple"), 170),
weightedFruits(Set("feijoa", "fig"), 201))


 //filtered List , Set sorted, contains "melon" as last member
val filteredWeightedFruitsList = List(
weightedFruits(Set("banana", "melon"), 250),
weightedFruits(Set("banana", "orange", "melon"), 270),
weightedFruits(Set("banana", "orange", "apple", "melon"), 365))

I'd like to go over each item in filteredWeightedFruitsList , find same items in weightedFruitsList, do a small manipulation and create a new List[weightedFruits]

My (not working yet) code :

def conf :Option[List[weightedFruits]] = {

  for (filtered <- filteredWeightedFruitsList){

     weightedFruitsList.find{

      case x if ( x.fruits equals filtered.fruits.dropRight(1) ) => return weightedFruits(x.fruits, x.weight / filtered.weight)]
      case _ => false
   }    
  }    
}

With this code I've two problems: 1) type mismatch; found : Unit required: Option

2) type mismatch; found : weightedFruits required: Option[List[weightedFruits]]

Any thoughts are welcome . Sorry if my question make you mad...

Last question maybe there is more efficient way to make this task ?

Thanks

Upvotes: 0

Views: 945

Answers (1)

chengpohi
chengpohi

Reputation: 14217

type mismatch; found : weightedFruits required: Option[List[weightedFruits]] is caused by your conf method doesn't return Option[List[weightedFruits]] type result. maybe you can try use for yield to do this.

def conf :List[weightedFruits] = for {
   f <- filteredWeightedFruitsList
   t <- weightedFruitsList.find(i => f.fruits.dropRight(1) == i.fruits)
} yield t.copy(weight = t.weight / f.weight)

copy method will copy case class, and override some fields by using name

Upvotes: 2

Related Questions