Skip to content

Commit 3a3f79f

Browse files
committed
optimize Gen.zipWith code generator
1 parent d77244a commit 3a3f79f

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

project/codegen.scala

+19-10
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,6 @@ object codegen {
3737
s"$g.flatMap(($t: $T) => $acc)"
3838
}
3939

40-
def flatMappedGeneratorsWithFun(i: Int, f: String, s: Seq[(String, String)]): String =
41-
s.init.foldRight(s"${s.last._2}.map { ${s.last._1} => $f(${vals(i)}) }") {
42-
case ((t, g), acc) =>
43-
val T = t.toUpperCase
44-
s"$g.flatMap(($t: $T) => $acc)"
45-
}
46-
4740
def vals(i: Int) = csv(idents("t", i))
4841

4942
def coImplicits(i: Int) = (1 to i).map(n => s"co$n: Cogen[T$n]").mkString(",")
@@ -114,14 +107,30 @@ object codegen {
114107
}
115108

116109
def zipWith(i: Int) = {
117-
val gens = flatMappedGeneratorsWithFun(i, "f", idents("t", i) zip idents("g", i))
110+
val f = "f"
111+
val tR = "R"
112+
val ts = idents("t", i) // Seq(t1, ... ti)
113+
val tTs = idents("T", i) // Seq(T1, ..., Ti)
114+
val gs = idents("g", i) // Seq(g1, ..., gi)
115+
val tTsCsv = csv(tTs) // "T1, ..., Ti"
116+
val tsCsv = csv(ts) // "t1, ..., ti"
117+
val tTts = tTs.zip(ts) // Seq((T1, t1), ..., (Ti, ti))
118+
val tTtgs = tTts.zip(gs) // Seq(((T1, t1), g1), ..., ((Ti, ti), gi))
119+
120+
val ((_, ti), gi) = tTtgs.last
121+
val gens =
122+
tTtgs.init.foldRight(s"$gi.map { $ti => $f($tsCsv) }") {
123+
case (((tT, t), g), acc) =>
124+
s"$g.flatMap(($t: $tT) => $acc)"
125+
}
126+
118127
s"""
119128
| /** Combines the given generators into a new generator of the given result type
120129
| * with help of the given mapping function. */
121-
| def zipWith[${types(i)},R](
130+
| def zipWith[$tTsCsv, $tR](
122131
| ${wrappedArgs("Gen", i)}
123132
| )(
124-
| f: (${types(i)}) => R
133+
| $f: ($tTsCsv) => $tR
125134
| ): Gen[R] =
126135
| $gens
127136
|""".stripMargin

0 commit comments

Comments
 (0)