Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:18
Show Gist options
  • Save dacr/6b37cdcbca409eba5a618b67ecc73594 to your computer and use it in GitHub Desktop.
Save dacr/6b37cdcbca409eba5a618b67ecc73594 to your computer and use it in GitHub Desktop.
scala3 feature examples - macros - inline if / published by https://github.com/dacr/code-examples-manager #2caea6b8-340f-45a1-923c-ac671afb6491/f6e64dc8fb4fa2b967dc83f3be2dbe7edaa5bfb9
// summary : scala3 feature examples - macros - inline if
// keywords : scala3, tutorial, macros, inline, meta-programming, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 2caea6b8-340f-45a1-923c-ac671afb6491
// created-on : 2024-03-17T08:46:55+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// Inspired from https://docs.scala-lang.org/scala3/guides/macros/inline.html
//> using scala "3.4.2"
inline def power(x: Double, inline n: Int): Double = {
inline if (n == 0) 1.0
else inline if (n % 2 == 1) x * power(x, n - 1)
else power(x * x, n / 2)
}
@main def go():Unit = {
println(power(2,3))
//val twoPowers = (n:Int)=> power(2,n) // Won't compile of course : Cannot reduce `inline if` because its condition is not a constant value
//println(twoPowers(8))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment