Jump to content

Enforced immutability: Difference between revisions

Rename Perl 6 -> Raku, alphabetize, minor clean-up
(Added C#)
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
Line 11:
</lang>
That declares that the number 123 is constant and may not be modified (not that the variable named 'one-two-three' is constant)
 
=={{header|ACL2}}==
All variables in ACL2 are constants, with the exception of those accessed using <code>(assign ...)</code> and accessed using <code>(@ ...)</code>
Line 124 ⟶ 125:
 
It is possible to remove the <tt>const</tt> qualifier of the type a pointer points to through a cast, but doing so will result in undefined behavior.
 
=={{header|C sharp}}==
Fields can be made read-only (a runtime constant) with the '''readonly''' keyword.
<lang csharp>readonly DateTime now = DateTime.Now;</lang>
When used on reference types, it just means the reference cannot be reassigned. It does not make the object itself immutable.<br/>
Primitive types can be declared as a compile-time constant with the '''const''' keyword.
<lang csharp>const int Max = 100;</lang>
 
Parameters can be made readonly by preceding them with the '''in''' keyword. Again, when used on reference types, it just means the reference cannot be reassigned.
<lang csharp>public void Method(in int x) {
x = 5; //Compile error
}</lang>
 
Local variables of primitive types can be declared as a compile-time constant with the '''const''' keyword.
<lang csharp>public void Method() {
const double sqrt5 = 2.236;
...
}</lang>
 
To make a type immutable, the programmer must write it in such a way that mutation is not possible. One important way to this is to use readonly properties. By not providing a setter, the property can only be assigned within the constructor.
<lang csharp>public string Key { get; }</lang>
On value types (which usually should be immutable from a design perspective), immutability can be enforced by applying the '''readonly''' modifier on the type. It will fail to compile if it contains any members that are not read-only.
<lang csharp>
public readonly struct Point
{
public Point(int x, int y) => (X, Y) = (x, y);
 
public int X { get; }
public int Y { get; }
}</lang>
 
=={{header|C++}}==
Line 163 ⟶ 194:
}
};</lang>
 
 
=={{header|C sharp}}==
Fields can be made read-only (a runtime constant) with the '''readonly''' keyword.
<lang csharp>readonly DateTime now = DateTime.Now;</lang>
When used on reference types, it just means the reference cannot be reassigned. It does not make the object itself immutable.<br/>
Primitive types can be declared as a compile-time constant with the '''const''' keyword.
<lang csharp>const int Max = 100;</lang>
 
Parameters can be made readonly by preceding them with the '''in''' keyword. Again, when used on reference types, it just means the reference cannot be reassigned.
<lang csharp>public void Method(in int x) {
x = 5; //Compile error
}</lang>
 
Local variables of primitive types can be declared as a compile-time constant with the '''const''' keyword.
<lang csharp>public void Method() {
const double sqrt5 = 2.236;
...
}</lang>
 
To make a type immutable, the programmer must write it in such a way that mutation is not possible. One important way to this is to use readonly properties. By not providing a setter, the property can only be assigned within the constructor.
<lang csharp>public string Key { get; }</lang>
On value types (which usually should be immutable from a design perspective), immutability can be enforced by applying the '''readonly''' modifier on the type. It will fail to compile if it contains any members that are not read-only.
<lang csharp>
public readonly struct Point
{
public Point(int x, int y) => (X, Y) = (x, y);
 
public int X { get; }
public int Y { get; }
}</lang>
 
=={{header|Clojure}}==
Line 374:
constant s = {1,2,3}
constant str = "immutable string"</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
In type declaration statements a PARAMETER attribute can be specified turning the data object into a named constant.
<lang fortran>real, parameter :: pi = 3.141593</lang>
Dummy arguments of procedures can be given an INTENT attribute. An argument with INTENT(IN) cannot be changed by the procedure
<lang Fortran>subroutine sub1(n)
real, intent(in) :: n</lang>
 
=={{header|F#}}==
Line 393 ⟶ 385:
 
Note that the <code>CONSTANT:</code> word does nothing to enforce immutability on the object it places on the stack, as it is functionally equivalent to a standard word definition with stack effect <code>( -- obj )</code>.
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
In type declaration statements a PARAMETER attribute can be specified turning the data object into a named constant.
<lang fortran>real, parameter :: pi = 3.141593</lang>
Dummy arguments of procedures can be given an INTENT attribute. An argument with INTENT(IN) cannot be changed by the procedure
<lang Fortran>subroutine sub1(n)
real, intent(in) :: n</lang>
 
=={{header|Go}}==
Line 646:
 
Here we can see that in the implementation the new type for immutable strings is defined with <code>type im_string = string</code>, and the definition of this type is hidden in the interface with <code>type im_string</code>.
 
 
=={{header|Oforth}}==
Line 705 ⟶ 704:
"c" => 3
);</lang>
 
=={{header|Perl 6}}==
You can create constants in Perl 6 with constant:
<lang perl6>constant $pi = 3.14159;
constant $msg = "Hello World";
 
constant @arr = (1, 2, 3, 4, 5);</lang>
 
Immutability is abstract enough that you can define an infinite constant lazily:
<lang perl6>constant fibonacci = 0, 1, *+* ... *;</lang>
 
Variables are considered mutable by default, but may be marked as readonly after initialization:
<lang perl6>my $pi := 3 + rand;</lang>
Unlike variables, formal parameters are considered readonly by default even if bound to a mutable container.
<lang perl6>sub sum (Num $x, Num $y) {
$x += $y; # ERROR
}
 
# Explicitly ask for pass-by-reference semantics
sub addto (Num $x is rw, Num $y) {
$x += $y; # ok, propagated back to caller
}
 
# Explicitly ask for pass-by-value semantics
sub sum (Num $x is copy, Num $y) {
$x += $y; # ok, but NOT propagated back to caller
$x;
}</lang>
A number of built-in types are considered immutable value types, including:
<pre>Str Perl string (finite sequence of Unicode characters)
Int Perl integer (allows Inf/NaN, arbitrary precision, etc.)
Num Perl number (approximate Real, generally via floating point)
Rat Perl rational (exact Real, limited denominator)
FatRat Perl rational (unlimited precision in both parts)
Complex Perl complex number
Bool Perl boolean
Exception Perl exception
Block Executable objects that have lexical scopes
Seq A list of values (can be generated lazily)
Range A pair of Ordered endpoints
Set Unordered collection of values that allows no duplicates
Bag Unordered collection of values that allows duplicates
Enum An immutable Pair
Map A mapping of Enums with no duplicate keys
Signature Function parameters (left-hand side of a binding)
Capture Function call arguments (right-hand side of a binding)
Blob An undifferentiated mass of ints, an immutable Buf
Instant A point on the continuous atomic timeline
Duration The difference between two Instants</pre>
These values, though objects, can't mutate; they may only be "changed" by modifying a mutable container holding one of them to hold a different value instead. (In the abstract, that is. In the interests of efficiency, a string or list implementation would be allowed to cheat as long as it doesn't get caught cheating.) Some of these types have corresponding "unboxed" native representations, where the container itself must carry the type information since the value can't. In this case, it's still the container that might be
considered mutable as an lvalue location, not the value stored in that location.
 
By default, object attributes are not modifiable from outside a class, though this is usually viewed more as encapsulation than as mutability control.
 
=={{header|Phix}}==
Line 930 ⟶ 876:
TypeError: 'Immut' object does not support item assignment
>>></lang>
 
=={{header|Racket}}==
 
Line 941 ⟶ 888:
<lang Racket>(struct coordinate (x y)) ; immutable struct</lang>
mutable struct definitions need to explicitly use a <tt>#:mutable</tt>, keyword next to a field to specify it as mutable, or as an option to the whole struct to make all fields mutable.
 
=={{header|Raku}}==
(formerly Perl 6)
You can create constants in Perl 6 with constant:
<lang perl6>constant $pi = 3.14159;
constant $msg = "Hello World";
 
constant @arr = (1, 2, 3, 4, 5);</lang>
 
Immutability is abstract enough that you can define an infinite constant lazily:
<lang perl6>constant fibonacci = 0, 1, *+* ... *;</lang>
 
Variables are considered mutable by default, but may be marked as readonly after initialization:
<lang perl6>my $pi := 3 + rand;</lang>
Unlike variables, formal parameters are considered readonly by default even if bound to a mutable container.
<lang perl6>sub sum (Num $x, Num $y) {
$x += $y; # ERROR
}
 
# Explicitly ask for pass-by-reference semantics
sub addto (Num $x is rw, Num $y) {
$x += $y; # ok, propagated back to caller
}
 
# Explicitly ask for pass-by-value semantics
sub sum (Num $x is copy, Num $y) {
$x += $y; # ok, but NOT propagated back to caller
$x;
}</lang>
A number of built-in types are considered immutable value types, including:
<pre>Str Perl string (finite sequence of Unicode characters)
Int Perl integer (allows Inf/NaN, arbitrary precision, etc.)
Num Perl number (approximate Real, generally via floating point)
Rat Perl rational (exact Real, limited denominator)
FatRat Perl rational (unlimited precision in both parts)
Complex Perl complex number
Bool Perl boolean
Exception Perl exception
Block Executable objects that have lexical scopes
Seq A list of values (can be generated lazily)
Range A pair of Ordered endpoints
Set Unordered collection of values that allows no duplicates
Bag Unordered collection of values that allows duplicates
Enum An immutable Pair
Map A mapping of Enums with no duplicate keys
Signature Function parameters (left-hand side of a binding)
Capture Function call arguments (right-hand side of a binding)
Blob An undifferentiated mass of ints, an immutable Buf
Instant A point on the continuous atomic timeline
Duration The difference between two Instants</pre>
These values, though objects, can't mutate; they may only be "changed" by modifying a mutable container holding one of them to hold a different value instead. (In the abstract, that is. In the interests of efficiency, a string or list implementation would be allowed to cheat as long as it doesn't get caught cheating.) Some of these types have corresponding "unboxed" native representations, where the container itself must carry the type information since the value can't. In this case, it's still the container that might be
considered mutable as an lvalue location, not the value stored in that location.
 
By default, object attributes are not modifiable from outside a class, though this is usually viewed more as encapsulation than as mutability control.
 
=={{header|REXX}}==
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.