Scala List.filter with two conditions, applied only once

前端 未结 4 412
旧时难觅i
旧时难觅i 2021-02-04 13:18

Don\'t know if this is possible, but I have some code like this:

val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
val evens = list.filter { e => e % 2 =         


        
4条回答
  •  悲哀的现实
    2021-02-04 13:59

    You could use function composition. someCondition here is only called once, when deciding which function to compose with:

    def modN(n: Int)(xs: List[Int]) = xs filter (_ % n == 0)
    
    val f = modN(2) _ andThen (if (someCondition) modN(3) else modN(5))
    
    val result = f(list)
    

    (This doesn't do what you want - it still traverses the list twice)

    Just do this:

    val f: Int => Boolean = if (someCondition) { _ % 3 == 0 } else { _ % 5 == 0 }
    val result = list filter (x => x % 2 == 0 && f(x))
    

    or maybe better:

    val n = if (someCondition) 3 else 5
    val result = list filter (x => x % 2 == 0 && x % n == 0)
    

提交回复
热议问题