在一个scala列表中查找元素,并且知道哪个谓词已经被满足 [英] Finding elements in a scala list and also know which predicate has been satisfied

查看:134
本文介绍了在一个scala列表中查找元素,并且知道哪个谓词已经被满足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在scala中遇到以下问题。我必须找到列表中的第一个元素,它满足OR中有两个条件的谓词函数。问题是我想获得元素,但也知道两个条件中的哪一个已经满足。这里有一个简单的例子:

$ $ $ $ $ $ $ $ $ $ $ $ $ $列表(A,B,AA,BB )
val l2 = List(AA,BB,A,B)

def c1(s:String)= s.startsWith(B)
def c2(s:String)= s.length == 2

println(l1.find(s => c1(s)|| c2(s)))
println(l2.find(s => c1(s)|| c2(s)))





 一些(B)
一些(AA)


$ b

对于l1的情况,我希望有一些返回值(例如一个字符串),表示c1被满足(c2为l2的情况)。
一个可能的解决方案可能是在测试之前定义一个var,并将其设置在c1和c2函数中,但是我想找到一个更功能样式的解决方案,或许返回一个Tuple,如:发现,条件满意)。


感谢您的帮助

解决方案

<



Scala 2.8:

  def find2p [T](l:List [T],p1:T => Boolean,p2:T => Boolean)= 
l.view.map(el =>(el,p1 ),p2(el)))。find(t => t._2 || t._3)

Scala 2.7:

pre $ def $ find $ p $ ,p2:T =>布尔)=
l.projection.map(el =>(el,p1(el),p2(el)))。 t $ __3)

视图 / projection 确保映射将按需完成,而不是应用于整个列表。


I have the following problem in scala. I have to find the first element in al list which satisfies a predicate function with two conditions in OR. The problem is that I would like to get the element but also know which of the two conditions has been satisfied. Here is a simple example:

val l1 = List("A", "B", "AA", "BB")
val l2 = List("AA", "BB", "A", "B")

def c1(s: String) = s.startsWith("B")
def c2(s: String) = s.length == 2

println(l1.find(s => c1(s) || c2(s)))
println(l2.find(s => c1(s) || c2(s)))

result is:

Some(B)
Some(AA)

For the l1 case I would like to have some return value (a String for example) indicating that c1 was satisfied (c2 for the l2 case). A possible solution could be to define a var before the test and set it within the c1 and c2 functions, but I would like to find a more "functional style" solution, maybe something that return a Tuple like: (element found, condition satisfied).

Thanks in advance for the help

解决方案

I'd do this:

Scala 2.8:

def find2p[T](l: List[T], p1: T => Boolean, p2: T => Boolean) = 
  l.view.map(el => (el, p1(el), p2(el))).find(t => t._2 || t._3)

Scala 2.7:

def find2p[T](l: List[T], p1: T => Boolean, p2: T => Boolean) = 
  l.projection.map(el => (el, p1(el), p2(el))).find(t => t._2 || t._3)

The view/projection ensures that the mapping will be done on-demand, instead of being applied to the whole list.

这篇关于在一个scala列表中查找元素,并且知道哪个谓词已经被满足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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