I'm trying to learn functional programming and Scala, following through Project Euler problems.
I'm solving get the sum of multiples x & y in a list. So for a list [1,2,3,4,5,6,7,8,9]
get multiples of 3, 5 returns 3, 5, 6 and 9, the sum being 23.
- I'm accepting two parameters
list
andmultiples
- Mapping multiples to list of functions, that test if input is a multiple
- Filtering anything that returns true in the mapped multiples list
def multiplesOf(list: List[Int], multiples: List[Int]): List[Int] = {
def filterMultipleOf(x: Int) : Int => Boolean = (y: Int) => {
y % x == 0
}
val multiplesFilter = multiples.map(filterMultipleOf(_))
list.filter( int => multiplesFilter.exists(mOf => mOf(int)))
}
scala> multiplesOf(List.range(1,10), List(3,5)).sum
res: Int = 23
My main question: Is this the Scale/FP way?
Is defining filterMultipleOf
inside my function still pure? Is there a better way to express this in Scala or FP?