筛选并报告多个谓词 [英] filter and report multiple predicates

查看:83
本文介绍了筛选并报告多个谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一种Scala修饰性的问题。需要根据对象的属性过滤包含对象的列表。我需要报告该属性的第一次检查是否导致一个空列表。简化代码:

This is a kind of cosmetic Scala question. A list with objects needs to be filtered on the objects' attributes. I need to report if the first check on the attribute results in an empty list. Simplified code:

case class Account (id: Int, balance: Float)

def doFilter(list: List[Account], focusId: Int, thresHold: Float): List[Account] = {
  list.filter(_.id == focusId)
  // ## if at this point if the list is empty, an error log is required.
    .filter(_.balance >= thresHold)
}

var accounts = List(Account(1, 5.0f), Account(2, -1.0f), Account(3, 10f), Account(4, 12f))

println(s"result ${doFilter(accounts, 1, 0f)}")

当然,我可以拆分过滤器语句并检查中间结果,但我希望我可以使用更多scala方法。

Of course I can split up the filter statements and check the intermediate result but I was hoping I could do it more scala way.. I thought something like.

list.filter(_.id == focusId) 
match { case List() => { println "error"; List()}
case _ => _}

但这是行不通的。

推荐答案

下面的代码是对 Rex Kerr的这个答案

implicit class KestrelPattern[A](private val repr: A) extends AnyVal {
  def tee[B](f: A => B) = { f(repr); repr } // B is thrown away (Unit)
}

他称之为点击。我选择 tee 是因为它与unix tee命令相似。

He called it tap. I chose tee because of the similarity to the unix tee command.

用法:

scala> List[Int](3,5,7).tee{x => if (x.isEmpty) println("ERROR")}.sum
res42: Int = 15

scala> List[Int]().tee{x => if (x.isEmpty) println("ERROR")}.sum
ERROR
res43: Int = 0

这篇关于筛选并报告多个谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆