Skip to content

Instantly share code, notes, and snippets.

@dacr
Created April 20, 2024 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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/ce18ac780a6d11949a8ea1180d342a65aa5d914c
// 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.0"
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