过滤和报告多个谓词 [英] filter and report multiple predicates

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

问题描述

这是一种 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 _ => _}

但这行不通.是否有一种功能(或流畅)的方式来实现所需的行为?

But that doesn't work. Is there a functional (or fluent) way to implement the desired behaviour?

推荐答案

以下代码是对 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)
}

他称之为tap.我选择了 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天全站免登陆