Created
April 20, 2024 13:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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