File tree Expand file tree Collapse file tree 2 files changed +24
-0
lines changed
tests/pos-macros/power-macro-2 Expand file tree Collapse file tree 2 files changed +24
-0
lines changed Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change
1
+ def test (x : Int ) = power(x, 5 )
2
+ def test (x : Double ) = power(x, 5 )
You can’t perform that action at this time.
0 commit comments