Skip to content

Commit cfc7347

Browse files
committed
Add type class power macro regression test
1 parent 968dd1b commit cfc7347

File tree

4 files changed

+51
-0
lines changed

4 files changed

+51
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
import scala.quoted.*
3+
4+
import math.Numeric.Implicits.infixNumericOps
5+
6+
inline def power[Num](x: Num, inline n: Int)(using num: Numeric[Num]) = ${powerCode('x, 'n)(using 'num)}
7+
8+
private def powerCode[Num: Type](x: Expr[Num], n: Expr[Int])(using Expr[Numeric[Num]])(using Quotes): Expr[Num] =
9+
powerCode(x, n.valueOrAbort)
10+
11+
private def powerCode[Num: Type](x: Expr[Num], n: Int)(using num: Expr[Numeric[Num]])(using Quotes): Expr[Num] =
12+
if (n == 0) '{ $num.one }
13+
else if (n % 2 == 0) '{
14+
given Numeric[Num] = $num
15+
val y = $x * $x
16+
${ powerCode('y, n / 2) }
17+
}
18+
else '{
19+
given Numeric[Num] = $num
20+
$x * ${powerCode(x, n - 1)}
21+
}
22+
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
def test(x: Int) = power(x, 5)
2+
def test(x: Double) = power(x, 5)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
import scala.quoted.*
3+
4+
import math.Numeric.Implicits.infixNumericOps
5+
6+
inline def power[Num](x: Num, inline n: Int)(using num: Numeric[Num]) = ${powerCode('x, 'n)(using 'num)}
7+
8+
private def powerCode[Num: Type](x: Expr[Num], n: Expr[Int])(using Expr[Numeric[Num]])(using Quotes): Expr[Num] =
9+
powerCode(x, n.valueOrAbort)
10+
11+
private def powerCode[Num: Type](x: Expr[Num], n: Int)(using num: Expr[Numeric[Num]])(using Quotes): Expr[Num] =
12+
if (n == 0) '{ $num.one }
13+
else if (n % 2 == 0) '{
14+
withGiven($num) {
15+
val y = $x * $x
16+
${ powerCode('y, n / 2) }
17+
}
18+
}
19+
else '{
20+
withGiven($num) {
21+
$x * ${powerCode(x, n - 1)}
22+
}
23+
}
24+
25+
inline def withGiven[U, T](inline x: T)(inline body: T ?=> U): U = body(using x)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
def test(x: Int) = power(x, 5)
2+
def test(x: Double) = power(x, 5)

0 commit comments

Comments
 (0)