Scala 实现列表中奇数求和

1, 用flatMap 来实现

scala> val oddSum = (x: Int) => if(x%2!=0) Some(x) else None
oddSum: Int => Option[Int] = <function1>


scala> List(1,2,3,4,5,6).flatMap(x=>oddSum(x))
res39: List[Int] = List(1, 3, 5)


scala> List(1,2,3,4,5,6).flatMap(x=>oddSum(x)).foldLeft(0)((sum, i) => sum + i)
res40: Int = 9


2, 用filter来实现

scala> List(1,2,3,4,5,6).filter(_%2!=0)
res41: List[Int] = List(1, 3, 5)


scala> List(1,2,3,4,5,6).filter(_%2!=0).foldLeft(0)((sum,i) => sum +i )
res42: Int = 9


3, 用partition来实现

scala> List(1,2,3,4,5,6).partition(_%2!=0)._1
res43: List[Int] = List(1, 3, 5)


scala> List(1,2,3,4,5,6).partition(_%2!=0)._1.foldLeft(0)((sum ,i) => sum + i)
res44: Int = 9


4, 只用foldLeft

scala> List(1,2,3,4,5,6).foldLeft(0)((sum, i) => if(i%2==1) sum + i else sum)
res48: Int = 9




你可能感兴趣的:(scala,filter,partition,flatmap,foldLeft)