Skip to content

Add simple power test for patmat #7619

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions tests/run-macros/quote-matcher-power.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
32.0
512.0
2.0
1.0
64.0
35 changes: 35 additions & 0 deletions tests/run-macros/quote-matcher-power/Macro_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import scala.quoted._
import scala.quoted.matching._

object Macros {

def power_s(x: Expr[Double], n: Int)(given QuoteContext): Expr[Double] =
if (n == 0) '{1.0}
else if (n % 2 == 1) '{ $x * ${power_s(x, n - 1)} }
else '{ val y = $x * $x; ${power_s('y, n / 2)} }

inline def power(x: Double, inline n: Int): Double =
${power_s('x, n)}

def power2(x: Double, y: Double): Double = if y == 0.0 then 1.0 else x * power2(x, y - 1.0)

inline def rewrite(expr: => Double): Double = ${rewrite('expr)}

// simple, 1-level, non-recursive rewriter for exponents
def rewrite(expr: Expr[Double])(given QuoteContext): Expr[Double] = {
val res = expr match {
// product rule
case '{ power2($a, $x) * power2($b, $y)} if a.matches(b) => '{ power2($a, $x + $y) }
// rules of 1
case '{ power2($a, 1)} => a
case '{ power2(1, $a)} => '{ 1.0 }
// rule of 0
case '{ power2($a, 0)} => '{ 1.0 }
// power rule
case '{ power2(power2($a, $x), $y)} => '{ power2($a, $x * $y ) }
case _ => expr
}
println(res.show)
res
}
}
17 changes: 17 additions & 0 deletions tests/run-macros/quote-matcher-power/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Macros._

object Test {

def main(args: Array[String]): Unit = {
val x = 2
println(power(x, 5))

println(rewrite{ power2(2.0, 5.0) * power2(2.0, 4.0) })

println(rewrite{ power2(2.0, 1.0) })

println(rewrite{ power2(1.0, 1000) })

println(rewrite{ power2(power2(2.0, 2.0), 3.0) })
}
}