Compile-time calculation: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
(New post.) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(8 intermediate revisions by 3 users not shown) | |||
Line 838:
=={{header|Java}}==
<pre>
The Java compiler is able to calculate expressions that contain constant variables
<syntaxhighlight lang="">▼
and certain operators during code compilation.
As defined in the Java language specification,
the following operators and expressions may be used for constant expressions:
Unary operators: +, -, ~, !
Multiplicative operators: *, /, %
Additive operators: +, –
Shift operators: <<, >>, >>>
Relational operators: <, <=, >, >=
Equality operators: ==, !=
Bitwise and logical operators: &, ^, |
Conditional-and and the conditional-or operator: &&, ||
Ternary conditional operator: ?:
Parenthesized expressions whose contained expression is a constant expression
Simple names that refer to constant variables
</pre>
▲<syntaxhighlight lang="java">
public final class CompileTimeCalculation {
Line 848 ⟶ 863:
public static void main(String[] aArgs) {
System.out.println(tenFactorial);
}
private static int tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
}
Line 861 ⟶ 872:
<pre>
3628800
</pre>
Line 1,378 ⟶ 1,387:
Like Perl 5, we also have a BEGIN block, but it also works to introduce a blockless statement,
the value of which will be stored up to be used
<syntaxhighlight lang="raku" line> say
=={{header|REXX}}==
Line 1,450 ⟶ 1,459:
=={{header|Scala}}==
Scala 3 supports proper compile time evaluation
<syntaxhighlight lang="scala">
transparent inline def factorial(inline n: Int): Int =
inline n match
case 0 => 1
case _ => n * factorial(n - 1)
inline val factorial10/*: 3628800*/ = factorial(10)
</syntaxhighlight>
Alternative version that works with Scala 2:
<syntaxhighlight lang="scala">object Main extends {
val tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
Line 1,708 ⟶ 1,731:
Not that it makes much difference in practice as the compiler which is written in C is so quick (at least with scripts of moderate length and on modern hardware) that the compile and runtime stages are indistinguishable to the user.
<syntaxhighlight lang="
System.print(factorial10)</syntaxhighlight>
|