Scala条件列表构造 [英] Scala conditional list construction

查看:121
本文介绍了Scala条件列表构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我刚刚记住flatten与我的过滤器和地图有相同的效果



我使用Scala 2.9.2,并希望构建考虑以下情况,其中cond是一个函数,它使用谓词p和类型T的值(在这种情况下为t3):



p>

  t1 :: t2 :: cond(p,t3):: t4 
pre>

我想要的行为如下。如果p为真,则应该给出:

 列表[T](t1,t2,t3,t4)

如果p的计算结果为false,则应提供:

 列出[T](t1,t2,t4)



可能是想着这完全是错误的方式,但我努力想出一个优雅的解决方案。我可以涉及选项无处不在,然后过滤,但这使得代码更难读:

  def cond [T] := Boolean,v:T):Option [T] = 
{
p match
{
case true =>一些(v)
case false =>无
}
}

这允许以下操作:

  scala> (Some(1):: Some(2):: cond(true,3):: Some(4):: Nil).flatten 
res4:List [Int] = List(1, 4)

scala> (Some(1):: Some(2):: cond(false,3):: Some(4):: Nil).flatten
res5:List [Int] = List(1,

然而,它不是最优雅的解决方案,因为它要求用户包装所有的非 - some()中的条件元素,还要记住在最后做flatten。任何人都可以想出更优雅的解决方案?

解决方案

  @inline def cond [T](p:=> Boolean,v:T):List [T] = if (p)v :: Nil else Nil 

,然后使用它们:

 列表(1,2,3)++ cond(false,3)++列表(4)


EDIT: I've just remembered that flatten has the same effect as my filter and map

I'm using Scala 2.9.2, and would like to construct a list based on some conditions.

Consider the following, where cond is some function taking a predicate p and a value of type T (in this case t3):

t1 :: t2 :: cond( p, t3 ) :: t4

The behaviour I want is as follows. If p is true, this should give:

List[T]( t1, t2, t3, t4 )

If p evaluates to false, this should give:

List[T]( t1, t2, t4 )

I'm probably thinking about this completely the wrong way, but I'm struggling to come up with an elegant solution. I could involve Options everywhere and then filter, but that's makes the code rather harder to read:

def cond[T]( p : => Boolean, v : T ) : Option[T] =
{
    p match
    {
        case true => Some( v )
        case false => None
    }
}

This allows the following:

scala> ( Some( 1 ) :: Some( 2 ) :: cond( true, 3 ) :: Some( 4 ) :: Nil ).flatten
res4: List[Int] = List(1, 2, 3, 4)

scala> ( Some( 1 ) :: Some( 2 ) :: cond( false, 3 ) :: Some( 4 ) :: Nil ).flatten
res5: List[Int] = List(1, 2, 4)

However, it's not the most elegant solution, as it requires the user to wrap all of the their non-conditional elements in Some( ) and also to remember to do the flatten at the end. Can anyone think of a more elegant solution?

解决方案

How about yielding a Lists?

@inline def cond[T]( p : => Boolean, v : T ) : List[T] = if(p) v::Nil else Nil

and then using them as this:

List(1,2,3) ++ cond(false, 3 ) ++ List(4)

这篇关于Scala条件列表构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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