修改条件为true的列表中的元素

时间:2016-01-14 13:09:57

标签: scala functional-programming combinations higher-order-functions

var data = "<?php echo json_encode($data['value']);?>"

有没有组合器/更高阶函数的方法来做到这一点?像:

case class Person(name: String, age: Int, qualified: Boolean = false)

val people: List[Person] = ....

val updated: List[Person] = people.map(person => 
  if (person.age >= 25) 
    person.copy(qualified=true) 
  else
    person  // unmodified
))

// Setting every person above 25 y.o. as qualified

它就像条件people.updateWhere(_.age >= 25, _.copy(qualified=true)) 。大多数元素都是未修改的,但满足条件的元素会被修改/&#34;映射&#34;。

2 个答案:

答案 0 :(得分:1)

据我所知,没有这样的事情,虽然你可以通过隐式转换来实现:

implicit class ListOps[A](self: List[A]) extends AnyVal {
  def updateIf(predicate: A => Boolean, mapper: A => A): List[A] = {
    self.map(el => if (predicate(el)) mapper(el) else el)
  }
}

测试:

@ case class Person(name: String, age: Int, qualified: Boolean = false)
defined class Person
@  val people = List(Person("A", 3, false), Person("B", 35, false))
people: List[Person] = List(Person("A", 3, false), Person("B", 35, false))
@ people.updateIf(_.age >= 25, _.copy(qualified=true))
res3: List[Person] = List(Person("A", 3, false), Person("B", 35, true))

答案 1 :(得分:1)

也许我错过了什么,但这只是一个标准map。我会采用这样一个简单的方法:

scala> case class Person(name: String, age: Int, qualified: Boolean = false)
defined class Person

scala> val people = List(Person("John", 25), Person("Frank", 30))
people: List[Person] = List(Person(John,25,false), Person(Frank,30,false))

scala> def qualifyIf(p: Person)(pred: Person => Boolean) = if (pred(p)) p.copy(qualified = true) else p
qualifyIf: (p: Person)(pred: Person => Boolean)Person

scala> people.map(qualifyIf(_)(_.age > 25))
res1: List[Person] = List(Person(John,25,false), Person(Frank,30,true))

如果您愿意,可以将qualifyIf范围放入Person随播广告对象,甚至是Person案例类本身。

catsScalaz中可能会有一些与您正在寻找的内容完全相同的内容,但除非您已经使用过这些库,否则为此引入它们并不是一件好事