Scala partial functions and combination of partial functions
We have list of Partial Functions pf0-pf3, each has a personal domain area.
1) combine functions "manually"
val sqv: Seq[Int] = (-5 to 20 by 1).toList
val pf0: PartialFunction[Int,Int] = {case i if i < 0 => 0}
val pf1: PartialFunction[Int,Int] = {case i if i >= 0 && i <= 5 => i + 10 }
val pf2: PartialFunction[Int,Int] = {case i if i > 5 && i <= 10 => i + 2 }
val pf3: PartialFunction[Int,Int] = {case i if i > 10 => i - 1 }
1) combine functions "manually"
val f = pf0 orElse pf1 orElse pf2 orElse pf3
val r1 = sqv map f
output:
val sqv: Seq[Int] = List(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
val r1: Seq[Int] = List(0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
2) combine with foldLeft
val sqFunc: Seq[PartialFunction[Int,Int]] = Seq(pf0, pf1, pf2, pf3)
val ff: PartialFunction[Int,Int]= sqFunc.foldLeft(sqFunc.head){
case (acc,func) =>
acc orElse func
}
val r2 = sqv map ff
r1 == r2
output:
val r2: Seq[Int] = List(0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
val res1: Boolean = true
3) combine with recursive function
def recurs (acc: PartialFunction[Int,Int], s: Seq[PartialFunction[Int,Int]]):
PartialFunction[Int,Int] = {
if (s.isEmpty) acc
else recurs(acc orElse s.head, s.tail)
}
val fff = recurs(sqFunc.head, sqFunc.tail)
val r3 = sqv map fff
r2 == r3
output:
val fff: PartialFunction[Int,Int] =
val r3: Seq[Int] = List(0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
val res3: Boolean = true
Комментарии
Отправить комментарий