0

Having this:

name  |  sex
Peter |  man
Alice |  woman
John  |  man

I want to code a function that calculate the percentage of men and women, so I've coded this:

def gender(c: Seq[df]): (Double, Double) = {
    val percentages = c.groupBy(_.sex).map { case (sex, x) => val percentage = x.length * 100 
/c.length}
    (percentages (1), porcentages(0))
  }

But I'm getting this error:

scala.collection.immutable.Iterable[Unit] does not take parameters
    (percentages (1), percentages(0))

What is the problem here?

Coslada
  • 3
  • 2
  • 1
    `val foo = ???` is a statement, not an expression. It returns `Unit` just remove the `val percentage =` part so you have an **Iterable** of numbers. - Apart from that, the code should not provide the error you are seeing. - Oh, it seems `Iterable` doesn't have `apply` However, I am not sure how you finished with an `Iterable` if you started with a `Seq` – Luis Miguel Mejía Suárez Jul 06 '21 at 19:49
  • 2
    Strangely similar to https://stackoverflow.com/questions/68248208/scala-getting-the-percentage-of-the-number-of-objets-in-a-list Are you guys all working on some code tests?! – Gaël J Jul 06 '21 at 19:50
  • I am still trying to wrap my mind around that `c: Seq[df]`. Just how is this code working ? What is this `df`? – sarveshseri Jul 07 '21 at 02:36
  • @LuisMiguelMejíaSuárez Magical Scala collections try to give you "best possible types". "See how you always get the best possible type? If you `map` `Ints` to `Ints` you get again a `BitSet`, but if you map `Ints` to `Strings`, you get a `general Set`." - Martin; in his answer at https://stackoverflow.com/a/1728140/1151929 – sarveshseri Jul 07 '21 at 02:43
  • Does this answer your question? [Scala: Getting the percentage of the number of objets in a list](https://stackoverflow.com/questions/68248208/scala-getting-the-percentage-of-the-number-of-objets-in-a-list) – Jahnavi Paliwal Jul 07 '21 at 04:23
  • @sarveshseri yes I know, but this is the opposite. It went to a worse type, also `Seq` is not like `BitSet` it is general so it shouldn't have weird tricks. It sounds more like the code is incomplete or a bug in the IDE. – Luis Miguel Mejía Suárez Jul 07 '21 at 04:41
  • Any`map` transform on a `Map[A, B]` resulting in a in any type other than `Tuple2` always creates an `Iterable`. `Tuple2` will create a `Map`. And `groupBy` on `Seq` returns a `Map`. – sarveshseri Jul 07 '21 at 20:37

1 Answers1

1

The error is pretty clear, you have an Iterator[Unit] that you use as an Array.

First error is you build a val but doesn't return it:

val percentages = c.groupBy(_.sex).map { case (sex, x) =>
  val percentage = x.length * 100 /c.length
  percentage
}

Note that you can remove the val declaration entirely here.

Gaël J
  • 11,274
  • 4
  • 17
  • 32