Scala 转换A的惯用方法=>;序号[B]
我希望将单个值转换为多个“特征”的集合,而不使用可变数据结构来收集值。我喜欢这种使用模式匹配的幻想结构,但在第一次匹配后不会停止:Scala 转换A的惯用方法=>;序号[B],scala,Scala,我希望将单个值转换为多个“特征”的集合,而不使用可变数据结构来收集值。我喜欢这种使用模式匹配的幻想结构,但在第一次匹配后不会停止: scala> 2 multimatch { case i if i > 0 => "Positive" case i if i < 0 => "Negative" case i if (i % 2 == 0) => "Even" //yadda yadda } res0: Seq[java.lang.String]
scala> 2 multimatch {
case i if i > 0 => "Positive"
case i if i < 0 => "Negative"
case i if (i % 2 == 0) => "Even"
//yadda yadda
}
res0: Seq[java.lang.String] = List(Positive, Even)
scala>2多重匹配{
案例一如果i>0=>“正”
案例一如果i<0=>“负”
如果(i%2==0)=>偶数
//雅达雅达
}
res0:Seq[java.lang.String]=列表(正、偶数)
首先将特征定义为从Int到Option[String]的函数
val pos = (i:Int) => if (i > 0) Some("Positive") else None
val neg = (i:Int) => if (i < 0) Some("Negative") else None
val even = (i:Int) => if (i % 2 == 0) Some("Even") else None
然后使用flatmap获得应用于特定对象的特征列表
scala> characteristics.flatMap(f=>f(2))
res6: List[java.lang.String] = List(Positive, Even)
使用pimp模式、部分函数和重复参数,这就是我能达到的程度:
class MultiMatcher[A](a: A) {
def multiMatch[B](pfs: PartialFunction[A, B]*): Seq[B] = {
pfs.map(_.lift(a)).collect{ case Some(v) => v }
}
}
implicit def toMultiMatcher[A](a:A): MultiMatcher[A] = new MultiMatcher(a)
2 multiMatch (
{ case i if i > 0 => "Positive" },
{ case i if i < 0 => "Negative" },
{ case i if i % 2 == 0 => "Even" }
)
// returns Seq[java.lang.String] = ArrayBuffer(Positive, Even)
类多重匹配器[A](A:A){
def多重匹配[B](pfs:PartialFunction[A,B]*):顺序[B]={
收集{case Some(v)=>v}
}
}
隐式定义多匹配器[A](A:A):多匹配器[A]=新的多匹配器(A)
2多重匹配(
{如果i>0=>“正”}的情况i,
{如果i<0=>“负”}的情况i,
{如果i%2==0=>“偶数”}
)
//返回Seq[java.lang.String]=ArrayBuffer(正、偶数)
首先,定义一个多重匹配函数,如下所示:
scala> def multimatch[A,B]( value : A,ps: ( A => Boolean, B)*) =
| for ( p <- ps
| if (p._1(value))) yield p._2
multimatch: [A,B](value: A,ps: ((A) => Boolean, B)*)Seq[B]
scala>def多重匹配[A,B](值:A,ps:(A=>Boolean,B)*)=
|对于(p布尔,B)*)Seq[B]
然后,我们开始:
scala> multimatch(2,
| ( ((x :Int) => x > 0) -> "POSITIVE"),
| ( ((x :Int) => x < 0) -> "NEGATIVE"),
| ( ((x :Int) => x % 2 == 0) -> "EVEN")
| )
res4: Seq[java.lang.String] = ArrayBuffer(POSITIVE, EVEN)
scala>多重匹配(2,
|((x:Int)=>x>0)->“正”),
|((x:Int)=>x<0)->“负”),
|(((x:Int)=>x%2==0)->“偶数”)
| )
res4:Seq[java.lang.String]=ArrayBuffer(正、偶数)
或者,不那么杂乱:
scala> multimatch(2,
| ( (x :Int) => x > 0 , "POSITIVE"),
| ( (x :Int) => x < 0, "NEGATIVE"),
| ( (x :Int) => x % 2 == 0, "EVEN")
| )
res5: Seq[java.lang.String] = ArrayBuffer(POSITIVE, EVEN)
scala>多重匹配(2,
|((x:Int)=>x>0,“正”),
|((x:Int)=>x<0,“负”),
|((x:Int)=>x%2==0,“偶数”)
| )
res5:Seq[java.lang.String]=ArrayBuffer(正、偶数)
只有一个案例可以匹配。你需要嵌套它们,这样2就可以被识别为正数和偶数,或者我忽略了这一点?是的,我描述的是类似于模式匹配的东西,其中可以返回>1个匹配。为什么不pfs.flatMap(u.lift(a))
?隐式转换现在是“选择加入”,因此,在定义隐式转换之前,请添加import scala.language.implicitConversions
。
scala> multimatch(2,
| ( (x :Int) => x > 0 , "POSITIVE"),
| ( (x :Int) => x < 0, "NEGATIVE"),
| ( (x :Int) => x % 2 == 0, "EVEN")
| )
res5: Seq[java.lang.String] = ArrayBuffer(POSITIVE, EVEN)