0

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

Toren
  • 6,648
  • 12
  • 41
  • 62
  • Maybe worth noting that Sets are not sorted. For that you'd need [SortedSets](http://docs.scala-lang.org/overviews/collections/sets.html#sorted-sets) – hasumedic Sep 22 '16 at 16:11
  • Could you please give an example of desired function's signature, inputs, and output? Example `def add1(x: Int): Int`, input: `add1(42)`, output: `43`. – Kevin Meredith Sep 22 '16 at 16:55
  • desired function input two `List[weightedFuits]` ,the output is list too . `def conf ( filtered: List[weightedFruits] , full: List[weightedFruits]): List[weightedFruits]` – Toren Sep 22 '16 at 19:20

1 Answers1

2

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

chengpohi
  • 14,064
  • 1
  • 24
  • 42