lalakers4life - 5 months ago 29

Scala Question

I'm trying to print out all the factors of every number in a list.

Here is my code:

`def main(args: Array[String])`

{

val list_of_numbers = List(1,4,6)

def get_factors(list_of_numbers:List[Int]) : Int =

{

return list_of_numbers.foreach{(1 to _).filter {divisor => _ % divisor == 0}}

}

println(get_factors(list_of_numbers));

}

I want the end result to contain a single list that will hold all the numbers which are factors of any of the numbers in the list. So the final result should be (1,2,3,4,6). Right now, I get the following error:

`error: missing parameter type for expanded function ((x$1) => 1.to(x$1))`

return list_of_numbers.foreach{(1 to _).filter {divisor => _ % divisor == 0}}

How can I fix this?

Answer

A few things are wrong here.

First, `foreach`

takes a function `A => Unit`

as an argument, meaning that it's really just for causing side effects.

Second your use of `_`

, you can use _ when the function uses each argument once.

Lastly your expected output seems to be getting rid of duplicates (1 is a factor for all 3 inputs, but it only appears once).

```
list_of_numbers flatMap { i => (1 to i) filter {i % _ == 0 }} distinct
```

will do what you are looking for.

flatMap takes a function from `A => List[B]`

and produces a simple `List[B]`

as output, `list.distinct`

gets rid of the duplicates.