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>
Compile time calculation of constant values is possible in Java.
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: +, -, ~, !
import java.util.List;
Multiplicative operators: *, /, %
import java.util.stream.IntStream;
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);
System.out.println(word);
System.out.println(numbers);
}
private static int tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
private static String word = "Street".substring(1, 5);
private static List<Integer> numbers = IntStream.rangeClosed(1, 10).boxed().toList();
 
}
Line 861 ⟶ 872:
<pre>
3628800
tree
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</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 inas the surroundingan expression at run time:
 
<syntaxhighlight lang="raku" line> say( BEGIN [*] 2..10);</syntaxhighlight>
 
=={{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="ecmascriptwren">var factorial10 = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
 
System.print(factorial10)</syntaxhighlight>
9,482

edits