Enforced immutability: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Added C#)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(41 intermediate revisions by 20 users not shown)
Line 4:
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
<br><br>
 
=={{header|11l}}==
 
Prepend V/var keyword with minus sign to make variable immutable:
<syntaxhighlight lang="11l">-V min_size = 10</syntaxhighlight>
 
=={{header|6502 Assembly}}==
{{trans|Z80 Assembly}}
The 6502 has no hardware means of write-protecting areas of memory. Code and/or data are only immutable if they exist in ROM. Typically, a program run from floppy disk or CD-ROM is copied to the hardware's RAM and executed from there, while ROM cartridges (such as those on the NES) are often mapped directly into the 6502's address space and executed as ROM.
 
Side note: Trying to write to ROM at runtime will typically have no effect, but can also interact with memory-mapped ports resulting in undesired operation. (Some NES/Famicom cartridges would access mapper hardware by writing values to ROM)
<syntaxhighlight lang="6502asm">List:
byte $01,$02,$03,$04,$05</syntaxhighlight>
 
Labeled constants are also immutable, as the assembler replaces them with their equivalent values during the assembly process. The 6502 isn't aware those labels ever existed.
<syntaxhighlight lang="6502asm">bit_7 equ $80 ;every instance of "bit_7" in your source code is swapped with hexadecimal 80 during assembly</syntaxhighlight>
 
=={{header|68000 Assembly}}==
Most assemblers allow you to define labels which can refer to constant values for clarity.
<syntaxhighlight lang="68000devpac">bit7 equ %10000000
bit6 equ %01000000
 
MOVE.B (A0),D0
AND.B #bit7,D0
;D0.B contains either $00 or $80</syntaxhighlight>
 
When the program is being assembled, the assembler dereferences the labels and replaces them in-line with the labeled constants. They cannot be altered at runtime (except with self-modifying code).
 
=={{header|8th}}==
Items in 8th are constants if they are declared inside a word (function). Otherwise, they are mutable, unless the "const" word is used:
<langsyntaxhighlight lang="forth">
123 const var, one-two-three
</syntaxhighlight>
</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 16 ⟶ 44:
To declare a global constant, use:
 
<langsyntaxhighlight Lisplang="lisp">(defconst *pi-approx* 22/7)</langsyntaxhighlight>
 
Subsequent attempts to redefine the constant give an error:
Line 26 ⟶ 54:
=={{header|Ada}}==
Ada provides the <code>constant</code> keyword:
<langsyntaxhighlight Adalang="ada">Foo : constant := 42;
Foo : constant Blahtype := Blahvalue;</langsyntaxhighlight>
Types can be declared as limited: Objects of these types cannot be changed and also not compared nor copied:
<langsyntaxhighlight Adalang="ada">type T is limited private; -- inner structure is hidden
X, Y: T;
B: Boolean;
Line 35 ⟶ 63:
X := Y; -- illegal (cannot be compiled
B := X = Y; -- illegal
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
When a ''name'' is defined it can be identified as a constant value with an equality, eg pi = 355/113.
For a variable an assignment ":=" would be used instead, eg pi := 355/113;
<langsyntaxhighlight ALGOLlang="algol 68">INT max allowed = 20;
REAL pi = 3.1415 9265; # pi is constant that the compiler will enforce #
REF REAL var = LOC REAL; # var is a constant pointer to a local REAL address #
var := pi # constant pointer var has the REAL value referenced assigned pi #</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
It should be noted that Enforced immutability goes against the nature of AHK. However, it can be achieved using objects:
<langsyntaxhighlight AutoHotkeylang="autohotkey">MyData := new FinalBox("Immutable data")
MsgBox % "MyData.Data = " MyData.Data
MyData.Data := "This will fail to set"
Line 70 ⟶ 98:
return
}
}</langsyntaxhighlight>
You could still use ''ObjInsert/ObjRemove'' functions, since they are designed to bypass any custom behaviour implemented by the object. Also, technically you could still use the ''SetCapacity method'' to truncate the object, or the ''GetAddress method'' to modify the object using memory addresses.
 
=={{header|BASIC}}==
Many BASICs support the <code>CONST</code> keyword:
<langsyntaxhighlight lang="qbasic">CONST x = 1</langsyntaxhighlight>
 
Some flavors of BASIC support other methods of declaring constants. For example, [[FreeBASIC]] supports C-style defines:
<syntaxhighlight lang ="freebasic">#define x 1</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
BBC BASIC doesn't have named constants. The closest you can get is to use a function:
<langsyntaxhighlight lang="bbcbasic"> DEF FNconst = 2.71828182845905
PRINT FNconst
FNconst = 1.234 : REM Reports 'Syntax error'</langsyntaxhighlight>
 
=={{header|Bracmat}}==
All values (expressions) in Bracmat are immutable, except those that contain <code>=</code> operators.
<langsyntaxhighlight lang="bracmat">myVar=immutable (m=mutable) immutable;
changed:?(myVar.m);
lst$myVar
</syntaxhighlight>
</lang>
{{out}}
<pre>(myVar=
Line 98 ⟶ 126:
=={{header|C}}==
You can create simple constants using the C preprocessor:
<langsyntaxhighlight lang="c">#define PI 3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100</langsyntaxhighlight>
 
Alternatively, you can modify parameters and variables with the const keyword to make them immutable:
<langsyntaxhighlight lang="c">const char foo = 'a';
const double pi = 3.14159;
const double minsize = 10;
Line 121 ⟶ 149:
{
/* ... */
}</langsyntaxhighlight>
 
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|C#}}==
Fields can be made read-only (a runtime constant) with the '''readonly''' keyword.
<syntaxhighlight lang="csharp">readonly DateTime now = DateTime.Now;</syntaxhighlight>
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.
<syntaxhighlight lang="csharp">const int Max = 100;</syntaxhighlight>
 
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.
<syntaxhighlight lang="csharp">public void Method(in int x) {
x = 5; //Compile error
}</syntaxhighlight>
 
Local variables of primitive types can be declared as a compile-time constant with the '''const''' keyword.
<syntaxhighlight lang="csharp">public void Method() {
const double sqrt5 = 2.236;
...
}</syntaxhighlight>
 
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.
<syntaxhighlight lang="csharp">public string Key { get; }</syntaxhighlight>
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.
<syntaxhighlight lang="csharp">public readonly struct Point
{
public Point(int x, int y) => (X, Y) = (x, y);
 
public int X { get; }
public int Y { get; }
}</syntaxhighlight>
On a struct that is not made readonly, individual methods or properties can be made readonly by applying the '''readonly''' modifier on that member.
<syntaxhighlight lang="csharp">public struct Vector
{
public readonly int Length => 3;
}</syntaxhighlight>
 
=={{header|C++}}==
 
In addition to the examples shown in [[#C|C]], you can create a class whose instances contain instance-specific const members, by initializing them in the class's constructor.
<langsyntaxhighlight lang="cpp">#include <iostream>
 
class MyOtherClass
Line 149 ⟶ 211:
 
return 0;
}</langsyntaxhighlight>
 
You can also use the const keyword on methods to indicate that they can be applied to immutable objects:
<langsyntaxhighlight lang="cpp">class MyClass
{
private:
Line 162 ⟶ 224:
return x;
}
};</langsyntaxhighlight>
 
 
=={{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}}==
Everything in Clojure except for Java interop are immutable.
 
<langsyntaxhighlight Clojurelang="clojure">user> (def d [1 2 3 4 5]) ; immutable vector
#'user/d
user> (assoc d 3 7)
[1 2 3 7 5]
user> d
[1 2 3 4 5]</langsyntaxhighlight>
 
=={{header|COBOL}}==
Constants in COBOL are not stored in memory, but are closer to C's macros, by associating a literal with a name.
Prior to COBOL 2002, you could define figurative literals for characters only:
<langsyntaxhighlight lang="cobol"> ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9.</langsyntaxhighlight>
 
A new syntax was introduced in COBOL 2002 which allowed defining constants for other types.
<langsyntaxhighlight lang="cobol"> 01 Foo CONSTANT AS "Foo".</langsyntaxhighlight>
 
Prior to COBOL 2002, there were non-standard extensions available that also implemented constants. One extension was the the 78 level-number:
<langsyntaxhighlight lang="cobol"> 78 Foo VALUE "Foo".</langsyntaxhighlight>
Another was the <code>CONSTANT SECTION</code>:
<langsyntaxhighlight lang="cobol"> CONSTANT SECTION.
01 Foo VALUE "Foo".</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.random;
 
// enum allows to define manifest (compile-time) constants:
Line 289 ⟶ 320:
// Not allowed, the setter property is missing:
// t.x = 10; // Error: not a property t.x
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
Typed constants can be assigned to using the {$WRITABLECONST ON} or {J+} compiler directives (off by default).
<langsyntaxhighlight Delphilang="delphi">const
STR1 = 'abc'; // regular constant
STR2: string = 'def'; // typed constant</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
Dyalect supports creation of constants using "constlet" keyword:
 
<langsyntaxhighlight lang="dyalect">constlet pi = 3.14
constlet helloWorld = "Hello, world!"</langsyntaxhighlight>
 
A constant can contain a value of any type:
 
<langsyntaxhighlight lang="dyalect">constlet sequence = [1,2,3,4,5]</langsyntaxhighlight>
 
=={{header|E}}==
Line 315 ⟶ 346:
Variables are immutable unless declared with the '<code>var</code>' keyword.
 
<langsyntaxhighlight lang="e">def x := 1
 
x := 2 # this is an error</langsyntaxhighlight>
 
Below the surface, each variable name is bound to a Slot object, which can be thought of as a one-element collection. If the var keyword is used, then the slot object is mutable; else, immutable. It is never possible to change the slot a name is bound to.
Line 323 ⟶ 354:
Any object which is immutable and contains no immutable parts has the property DeepFrozen.
 
<langsyntaxhighlight lang="e">var y := 1
 
def things :DeepFrozen := [&x, 2, 3] # This is OK
 
def funnyThings :DeepFrozen := [&y, 2, 3] # Error: y's slot is not immutable</langsyntaxhighlight>
 
(The unary <code>&</code> operator gets the slot of a variable, and can be thought of almost exactly like C's <code>&</code>.)
Line 335 ⟶ 366:
Normally there is no need to enforce immutability in Ela - everything is immutable by default. Ela doesn't support mutable variables like imperative languages. All built-in data structures are immutable as well. The only way to create a mutable data structure is to use an unsafe module "cell", that implements reference cells in Ocaml style:
 
<langsyntaxhighlight lang="ela">open unsafe.cell
r = ref 0</langsyntaxhighlight>
 
Function mutate can be used to mutate a reference cell:
 
<syntaxhighlight lang ="ela">mutate r 1</langsyntaxhighlight>
 
In order to unwrap a value from a cell one can use a valueof function:
 
<syntaxhighlight lang ="ela">valueof r</langsyntaxhighlight>
 
=={{header|Elixir}}==
Line 363 ⟶ 394:
 
Erlang variables are immutable by nature. The following would be an error:
<langsyntaxhighlight lang="erlang">X = 10,
X = 20.</langsyntaxhighlight>
 
However, since = actually performs pattern matching, the following is permissible:
<langsyntaxhighlight lang="erlang">X = 10,
X = 10.</langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant n = 1
constant s = {1,2,3}
constant str = "immutable string"</langsyntaxhighlight>
 
=={{header|FortranF_Sharp|F#}}==
{{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#}}==
As a functional language, everything in F# is immutable by default. Interestingly, <code>const</code> is a reserved word but is non-functional.
<langsyntaxhighlight lang="fsharp">let hello = "Hello!"</langsyntaxhighlight>
 
=={{header|Factor}}==
Tuple slots may be declared <code>read-only</code>. For example, the <code>range</code> tuple declares its slots <code>read-only</code>:
<langsyntaxhighlight lang="factor">TUPLE: range
{ from read-only } { length read-only } { step read-only } ;</langsyntaxhighlight>
 
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|Forth}}==
Forth has constant, 2constant and fconstant for creating named constants. This can only be done for global scoped objects, not for function parameters.
<syntaxhighlight lang="forth">
256 constant one-hex-dollar
s" Hello world" 2constant hello \ "hello" holds the address and length of an anonymous string.
355 119 2constant ratio-pi \ 2constant can also define ratios (e.g. pi)
3.14159265e fconstant pi
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="fortran">real, parameter :: pi = 3.141593</syntaxhighlight>
Dummy arguments of procedures can be given an INTENT attribute. An argument with INTENT(IN) cannot be changed by the procedure
<syntaxhighlight lang="fortran">subroutine sub1(n)
real, intent(in) :: n</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#define IMMUT1 32767 'constants can be created in the preprocessor
dim as const uinteger IMMUT2 = 2222 'or explicitly declared as constants
</syntaxhighlight>
 
=={{header|Go}}==
Strings in Go are immutable. Attempts to modify them fail to compile:
<langsyntaxhighlight lang="go">package main
 
func main() {
s := "immutable"
s[0] = 'a'
}</langsyntaxhighlight>
<pre>
test.go:5: cannot assign to s[0]
Line 409 ⟶ 454:
=={{header|Haskell}}==
Since Haskell is purely functional everything is immutable by default.
<langsyntaxhighlight lang="haskell">pi = 3.14159
msg = "Hello World"</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
In Icon and Unicon pretty much everything can be changed. There really isn't an easy way to protect a variable from being changed. There are compile time constants created by ''$define'' (as shown); although, they can be explicitly undefined. String values themselves are immutable; however, manipulating them creates new string values. The effect is that the value assigned to a variable will change even though the value itself won't. For more see [[Icon%2BUnicon/Intro#Mutable_and_Immutable_Types|Mutable and Immutable Types]].
 
<langsyntaxhighlight Iconlang="icon">$define "1234"</langsyntaxhighlight>
 
=={{header|J}}==
Line 423 ⟶ 468:
The values associated with a J name can be modified, but that is a modification of the association, and the original value remains.
 
Note(Tangentially: note that J has a rich language for defining numeric constants. For example, 2*pi represented as a floating point number would be 2p1. These are analogous to names but can never be modified.)
 
<langsyntaxhighlight lang="j"> B=: A=: 'this is a test'
A=: '*' 2 3 5 7} A
A
th** *s*a test
B
this is a test</langsyntaxhighlight>
 
Names can also be made constant (that is, have their referent fixed), so that name, value, and association between name and value are immutable:<syntaxhighlight lang ="j"> C=: require'this is a testjmf'
C=: 'this is a test'
1 readonly_jmf_ 'C'
 
Line 439 ⟶ 485:
| C =:'some new value'
C
this is a test</langsyntaxhighlight>
 
=={{header|Java}}==
 
Variables in Java can be made immutable by using the <code>final</code> modifier (works on any type, primitive or reference):
<langsyntaxhighlight lang="java">final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; //this is fine
immutableInt = 6; //this is an error</langsyntaxhighlight>
 
Using final on a reference type means the reference cannot be reassigned, but does not necessarily mean that the object that it points to can't be changed:
<langsyntaxhighlight lang="java">final String immutableString = "test";
immutableString = new String("anotherTest"); //this is an error
final StringBuffer immutableBuffer = new StringBuffer();
immutableBuffer.append("a"); //this is fine and it changes the state of the object
immutableBuffer = new StringBuffer("a"); //this is an error</langsyntaxhighlight>
 
Whether an object can be modified is entirely up to whether the object provides either methods or non-final public/protected fields for mutation. Objects can be made immutable (in a sense that is more appropriate for this task) by making all fields <code>final</code> or <code>private</code>, and making sure that no methods modify the fields:
<langsyntaxhighlight lang="java">public class Immute{
private final int num;
private final String word;
Line 481 ⟶ 527:
}
//no "set" methods are given
}</langsyntaxhighlight>
In the <code>Immute</code> class above, the object pointed to by "buff" is still technically mutable, since its internal values can still be changed. The <code>private</code> modifier ensures that no other classes can access that variable. Some trickery needed to be done to ensure that no pointers to the actual mutable objects are passed out. Programmers should be aware of which objects that they use are mutable (usually noted in javadocs).
 
Line 490 ⟶ 536:
 
'''Update''': const is now a standard part of ES6 JavaScript, and works with all data types, including arrays, objects, and parameters. It is not, however, included in the ES5 standard.
<langsyntaxhighlight lang="javascript">const pi = 3.1415;
const msg = "Hello World";</langsyntaxhighlight>
 
=={{header|jq}}==
All values in jq are immutable. Sometimes the syntax may make it appear as though a value is being altered, but that is never the case. For example, consider the following pipeline:<langsyntaxhighlight lang="jq">
["a", "b"] as $a | $a[0] = 1 as $b | $a</langsyntaxhighlight>
 
Here, the result is ["a", "b"].
Line 502 ⟶ 548:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">const x = 1
x = π # ERROR: invalid ridefinition of constant x</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Line 517 ⟶ 563:
 
Here are some examples:
<langsyntaxhighlight lang="scala">// version 1.1.0
 
// constant top level property
Line 543 ⟶ 589:
println(mc.myInt)
mc.myFunc(0)
}</langsyntaxhighlight>
 
{{out}}
Line 553 ⟶ 599:
=={{header|Logtalk}}==
Logtalk supports both static and dynamic objects. Static objects are usually defined in source files. Object predicates are static by default. These objects can be defined locked against runtime modifications. For simplicity, the following example uses a prototype:
<langsyntaxhighlight lang="logtalk">
:- object(immutable).
 
Line 569 ⟶ 615:
 
:- end_object.
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
{{works with|lua|5.4}}
<syntaxhighlight lang="lua">local pi <const> = 3.14159265359</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
====Four Examples for Constant/Final modifiers====
Modules and functions in M2000 can change definitions with another definition (excluded subs and simple functions which are written at the end of module/function). So except for variables to be immutable we have to do something with modules and functions, only for members of groups (the user defined object in M2000).
 
Here we have four big modules (in a module say A). The first show how to use final in class/group definition, and what happen if we use class inheritance. The second module show how we can produce group from merging two others (here using With operator), and what happen with final members. The third module show how we use a reference to global constant, and how we can check type. The last module show constant with lambda functions.
 
<syntaxhighlight lang="m2000 interpreter">
module inheritanceByClass {
class alfa {
// final x is an object with the value of x,
// and interpreter trait it as read only variable
final x=100
// module just marked as final
module final tryme {
Print "Can't change"
}
}
class delta as alfa {
x=500
// modules and functions can alter definitions
// by a new one, unless they have marked final
// only for modules/functions as member of groups.
module tryme {
print "I win or not ?"
}
}
z=delta()
print z.x =100
z.tryme ' can't change
}
inheritanceByClass
 
module inheritanceByInstance {
class alfa {
final x=100
module final tryme {
Print "Can't change"
}
}
class delta {
x=500
module tryme {
print "I win or not ?"
}
}
 
z1=delta() with alfa()
// x is final, because delta be on top of alfa
print z1.x=100
try {
z1.x++
}
print z1.x=100
// that didn't hold for module. The final on module, close it.
z1.tryme ' can't change
z2=alfa() with delta()
// the following statements show every public identifier we make, including those non on scope.
// use List to see what we have as variables here (including members of z1, z2)
// use List ! to render ouput using proportional character spacing
// constant values displayed inside square brackets like this [100]
list !
modules ? // use this to see what functions we have until here
// x isn't final, because alfa be on top of delta,
// because x exist as number, can't change to const object.
print z2.x=500
try {
z2.x++
}
print z2.x=501
// that didn't hold for module. The final on module, close it.
z2.tryme ' can't change
}
inheritanceByInstance
 
Module ConstantGlobal {
global const p2 as single=1.57096
module inner {
const p2 // raise error if no global const p2 exist
print p2, type$(p2)="Constant"
def type(x)=type$(x)
print type(p2)="Single" // true
}
Inner
}
ConstantGlobal
module checkLambdaConstant {
const a=lambda (x)->x**2
print a(3)=9
try {
a=lambda (x)->x*5
}
print a(3)=9 // we can't copy to a a new lambda
module checkhere (z) {
print z(3)=9
try {
z=lambda (x)->x*5
}
print z(3)=15
}
// pass by copy of a, but not as constant
checkhere a
// assign to z a copy of a, but not as constant
z=a
print z(3)=9
try {
z=lambda (x)->x*5
}
print z(3)=15 // true
// redefinition of checkhere
module checkhere {
const z=stackitem() ' get a copy of top of stack
drop ' drop top of stack
print z(3)=9
try {
z=lambda (x)->x*5
}
print z(3)=9 // z not changed now
}
// now we pass a copy, but internal we make a constant lambda
checkhere a
// using by ref pass we send the const object, not a copy of it
// actually we send a weak reference, and at Read &z,
// the Read statement (Interpreter insert it automatic), make the link.
module checkByRef(&z) {
print z(3)=9
try {
z=lambda (x)->x*5
}
print z(3)=9 // z not changed
}
checkByRef &a
}
checkLambdaConstant
</syntaxhighlight>
 
====Partial constants by using enumeration types====
The value of a enumeration type may change to those of the same type (not the value type, the variable type)
 
 
<syntaxhighlight lang="m2000 interpreter">
enum constA {
x=10
y=30
}
// constB get two members of constA to same list, but x and y are defined once as ConstB
enum constB {
constA, z="ok"
}
// m is a ConstB type. X value exist in ConstB
def m as ConstB=x
 
module inner (z as constB) {
print z=10
try {
z=500
}
print z=10, eval$(z)="x"
check(z)
z++
print z=30, eval$(z)="y"
check(z)
z++
print z="ok", eval$(z)="z"
check(z)
try {
z=30 // ok 30 exist in enum constB list
}
check(z) // z is y now
sub check(z as constB)
select enum z // like a select case but for enumeration type to check names
case x ' check name of enum
print "it is x", z
case y
print "it is y", z
case z
print "it is z", z
end select
end sub
}
inner m
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Tau = 2*Pi;Protect[Tau]
{"Tau"}
 
Tau = 2
->Set::wrsym: Symbol Tau is Protected. </langsyntaxhighlight>
 
=={{header|MBS}}==
 
<langsyntaxhighlight lang="mbs">CONSTANT INT foo=640;</langsyntaxhighlight>
 
=={{header|Nemerle}}==
Everything is immutable by default.
<langsyntaxhighlight Nemerlelang="nemerle">def foo = 42; // immutable by default
mutable bar = "O'Malleys"; // mutable because you asked it to be</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var x = "mutablefoo" # Mutable variable
let y = "immutablefoo" # Immutable variable, at runtime
const z = "constantfoo" # Immutable constant, at compile time
Line 594 ⟶ 827:
x[0] = 'M'
y[0] = 'I' # Compile error: 'y[0]' cannot be assigned to
z[0] = 'C' # Compile error: 'z[0]' cannot be assigned to</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 610 ⟶ 843:
File <code>ImString.mli</code> containing the interface:
 
<langsyntaxhighlight lang="ocaml">type im_string
 
val create : int -> im_string
Line 624 ⟶ 857:
val index : im_string -> char -> int
val contains : im_string -> char -> bool
val print : im_string -> unit</langsyntaxhighlight>
 
File <code>ImString.ml</code> containing the "implementation":
 
<langsyntaxhighlight lang="ocaml">type im_string = string
 
let create = String.create
Line 643 ⟶ 876:
let of_string s = s
let to_string s = s
let print = print_string</langsyntaxhighlight>
 
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 668 ⟶ 900:
All these rules are checked at runtime and exceptions are raised if a piece of code breaks those immutability rules.
 
<langsyntaxhighlight Oforthlang="oforth">Object Class new: MyClass(a, b)
 
MyClass method: setA(value) value := a ;
Line 679 ⟶ 911:
MyClass new(ListBuffer new, 12) // KO : Not an immutable value.
ListBuffer new Constant new: T // KO : A constant cannot be mutable.
Channel new send(ListBuffer new) // KO : A mutable object can't be sent into a channel.</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 689 ⟶ 921:
=={{header|Perl}}==
The constant pragma allows you to create subroutines that always return the same value and that cannot be modified:
<langsyntaxhighlight lang="perl">use constant PI => 3.14159;
use constant MSG => "Hello World";</langsyntaxhighlight>
 
The module Readonly.pm provides a means of enforcing immutablity upon scalars and arrays, however, this imposes a considerable performance penalty:
 
<langsyntaxhighlight lang="perl">use Readonly;
 
Readonly::Scalar my $pi => 3.14159;
Line 704 ⟶ 936:
"b" => 2,
"c" => 3
);</langsyntaxhighlight>
 
=={{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}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant n = 1
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant s = {1,2,3}
<span style="color: #008080;">constant</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
constant str = "immutable string"</lang>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">str</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"immutable string"</span>
<!--</syntaxhighlight>-->
You can also optionally enforce one-off initial typechecks. In the following the compiler may infer the types and optimise away the typecheck, however for more complex initialisations this may lead to performance improvements later on, assuming eg a fatal `typecheck error, n is "no such directory"` is acceptable/wanted.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">constant</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">constant</span> <span style="color: #004080;">string</span> <span style="color: #000000;">str</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"immutable string"</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
You can create constants using the define function. This only works with scalars.
<langsyntaxhighlight lang="php">define("PI", 3.14159265358);
define("MSG", "Hello World");</langsyntaxhighlight>
 
Or: {{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php">const PI = 3.14159265358;
const MSG = "Hello World";</langsyntaxhighlight>
 
http://us.php.net/manual/en/language.constants.syntax.php
Line 778 ⟶ 967:
In PicoLisp it is a central design issue that the programmer is in control of everything, and thus can modify any value. Even program parts written in C or assembly can be changed on the fly.
The nearest thing would be to define a function, e.g.
<langsyntaxhighlight PicoLisplang="picolisp">: (de pi () 4)
-> pi
 
: (pi)
-> 4</langsyntaxhighlight>
but even this could be modified, e.g.:
<langsyntaxhighlight PicoLisplang="picolisp">: (set (cdr pi) 3)
-> 3
 
: (pi)
-> 3</langsyntaxhighlight>
 
=={{header|PL/I}}==
PL/I supports Named Constants. This avoids the default data attributes used when writing ''simple'' constants (such as 3).
<langsyntaxhighlight lang="pli">*process source attributes xref;
constants: Proc Options(main);
Dcl three Bin Fixed(15) Value(3);
Put Skip List(1/three);
Put Skip List(1/3);
End;</langsyntaxhighlight>
{{out}}
<pre> 0.33333332
Line 804 ⟶ 993:
=={{header|PowerBASIC}}==
Constants are declared by prefacing the variable name with <code>$</code> for strings and <code>%</code> for numeric variables:
<langsyntaxhighlight lang="powerbasic">$me = "myname"
%age = 35</langsyntaxhighlight>
 
=={{header|PureBasic}}==
PureBasic does not natively use immutable variables, only constants.
<langsyntaxhighlight PureBasiclang="purebasic">#i_Const1 = 11
#i_Const2 = 3.1415
#i_Const3 = "A'm a string"</langsyntaxhighlight>
 
However using an OO approach, PureBasic allows for creation of new variable classes such as immutable ones.
<langsyntaxhighlight PureBasiclang="purebasic">;Enforced immutability Variable-Class
 
Interface PBVariable ; Interface for any value of this type
Line 891 ⟶ 1,080:
;- And clean up
*v1\Destroy()
*v2\Destroy()</langsyntaxhighlight>
 
=={{header|Python}}==
Some datatypes such as strings are immutable:
<langsyntaxhighlight lang="python">>>> s = "Hello"
>>> s[0] = "h"
 
Line 901 ⟶ 1,090:
File "<pyshell#1>", line 1, in <module>
s[0] = "h"
TypeError: 'str' object does not support item assignment</langsyntaxhighlight>
 
While classes are generally mutable, you can define immutability by overriding __setattr__:
<langsyntaxhighlight lang="python">>>> class Immut(object):
def __setattr__(self, *args):
raise TypeError(
Line 929 ⟶ 1,118:
"'Immut' object does not support item assignment")
TypeError: 'Immut' object does not support item assignment
>>></langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Quackery does not enforce immutability. The majority of Quackery is immutable by design; operators and numbers are immutable, and nests are immutable insomuch as the words in the nest editing wordset treat them as immutable.
 
Certain objects; the ancillary stacks, the system dictionaries, and tables are mutable of necessity, and have a specific set of words, the ancillary stacks wordset, dedicated to handling them. The words in this wordset can also be applied to nests if the programmer chooses to disregard the guidelines for their use provided in The Book of Quackery. In short, enforcement is eschewed in favour of relying on the programmer's good sense.
 
=={{header|Racket}}==
 
Line 939 ⟶ 1,135:
 
In addition, new type definitions using <tt>struct</tt> are immutable by default:
<langsyntaxhighlight Racketlang="racket">(struct coordinate (x y)) ; immutable struct</langsyntaxhighlight>
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 Raku with <code>constant</code>:
<syntaxhighlight lang="raku" line>constant $pi = 3.14159;
constant $msg = "Hello World";
 
constant @arr = (1, 2, 3, 4, 5);</syntaxhighlight>
 
Immutability is abstract enough that you can define an infinite constant lazily:
<syntaxhighlight lang="raku" line>constant fibonacci = 0, 1, *+* ... *;</syntaxhighlight>
 
Variables are considered mutable by default, but may be marked as readonly after initialization:
<syntaxhighlight lang="raku" line>my $pi := 3 + rand;</syntaxhighlight>
Unlike variables, formal parameters are considered readonly by default even if bound to a mutable container.
<syntaxhighlight lang="raku" line>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;
}</syntaxhighlight>
A number of built-in types are considered immutable value types, including:
<pre>Str String (finite sequence of Unicode characters)
Int Integer (allows Inf/NaN, arbitrary precision, etc.)
Num Number (approximate Real, generally via floating point)
Rat Rational (exact Real, limited denominator)
FatRat Rational (unlimited precision in both parts)
Complex Complex number
Bool Boolean
Exception 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}}==
Programming note: &nbsp; The REXX language doesn't have immutable variables as such, but the method can be emulated with a simple subroutine. &nbsp; Immutable variables are set via a REXX subroutine which makes a shadow copy of the variable. &nbsp; Later, the same subroutine can be invoked (mutiple times if wanted) to check if any immutable variables have been altered (compromised). &nbsp; Three REXX variables are preempted: '''immutable.''', '''_''', and '''__''' &nbsp; (the last two are just used for temporary variables and any unused variable names can be used).
<langsyntaxhighlight lang="rexx">/*REXX program emulates immutable variables (as a post-computational check). */
call immutable '$=1' /* ◄─── assigns an immutable variable. */
call immutable ' pi = 3.14159' /* ◄─── " " " " */
Line 980 ⟶ 1,230:
return words(immutable.0) /*return number immutables. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error***' arg(2); say; exit arg(1) /*error msg.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 993 ⟶ 1,243:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Enforced immutability
 
Line 999 ⟶ 1,249:
assert( x = 10)
assert( x = 100 )
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,007 ⟶ 1,257:
=={{header|Ruby}}==
You can make things immutable at run-time with Ruby using the built-in Object#freeze method:
<langsyntaxhighlight lang="ruby">msg = "Hello World"
msg << "!"
puts msg #=> Hello World!
Line 1,027 ⟶ 1,277:
 
puts msg.frozen? #=> false
puts msg2.frozen? #=> true</langsyntaxhighlight>
Since Ruby version 2.1 freezing strings can give a performance boost.
There is no way to unfreeze a frozen object.
The freeze can not be canceled but the object of approximately the same contents not to freeze up can be gotten if using Object#dup.
<langsyntaxhighlight lang="ruby"># There are two methods in the copy of the object.
msg = "Hello World!".freeze
msg2 = msg.clone # Copies the frozen and tainted state of obj.
Line 1,038 ⟶ 1,288:
puts msg3 #=> Hello World!
puts msg2.frozen? #=> true
puts msg3.frozen? #=> false</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 1,044 ⟶ 1,294:
Rust <tt>let</tt> bindings are immutable by default. This will raise a compiler error:
 
<langsyntaxhighlight lang="rust">let x = 3;
x += 2;</langsyntaxhighlight>
 
You must declare a variable mutable explicitly:
 
<langsyntaxhighlight lang="rust">let mut x = 3;</langsyntaxhighlight>
Similarly, references are immutable by default e.g.
<langsyntaxhighlight lang="rust">let mut x = 4;
let y = &x;
*y += 2 // Raises compiler error. Even though x is mutable, y is an immutable reference.
Line 1,058 ⟶ 1,308:
// Note that though y is now a mutable reference, y itself is still immutable e.g.
let mut z = 5;
let y = &mut z; // Raises compiler error because y is already assigned to '&mut x'</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val pi = 3.14159
val msg = "Hello World"</langsyntaxhighlight>
 
=={{header|Scheme}}==
The easiest way of enforcing immutability is simply not importing mutative procedures (helpfully prefixed with <tt>!</tt>) when importing the main libraries.
It helps that imported variables are immutable by standard.
However, you might want to prevent yourself from accidentally calling <tt>set!</tt> on local variables for whatever reason.
Below is a <tt>syntax-case</tt> macro that uses variable transformers to disable <tt>set!</tt> calls on the given token, with a descriptive error message.
It can also be adapted to work with other mutative procedures.
The value itself is neatly tucked behind a hygienically mangled identifier that is impossible to directly reach.
 
This R6RS macro can be effortlessly ported to [[Racket]] by replacing <tt>make-variable-transformer</tt> with <tt>make-set!-transformer</tt> and <tt>(raise (syntax-violation ...))</tt> with <tt>(raise-syntax-error ...)</tt>.
<syntaxhighlight lang="scheme">(define-syntax define-constant
(syntax-rules ()
((_ id v)
(begin
(define _id v)
(define-syntax id
(make-variable-transformer
(lambda (stx)
(syntax-case stx (set!)
((set! id _)
(raise
(syntax-violation
'set! "Cannot redefine constant" stx #'id)))
((id . args) #'(_id . args))
(id #'_id)))))))))</syntaxhighlight>
Example use case:
<syntaxhighlight lang="scheme">(define-constant fnord 23)
;;
fnord
;; => 23
(+ fnord 5)
;; => 28
(set! fnord 42)
;; => Syntax error: set!: Cannot redefine constant in subform fnord of (set! fnord 42)</syntaxhighlight>
It works with procedures as well:
<syntaxhighlight lang="scheme">(define-constant square (lambda (n) (* n n)))
;;
square
;; => #<procedure square>
(square 5)
;; => 25
(set! square (lambda (n) (* n n n)))
;; => Syntax error: set!: Cannot redefine constant in subform square of (set! square (lambda (n) (* n n n)))</syntaxhighlight>
 
=={{header|Seed7}}==
Seed7 provides <code>const</code> definitons.
Constants can have any type:
<langsyntaxhighlight lang="seed7">const integer: foo is 42;
const string: bar is "bar";
const blahtype: blah is blahvalue;</langsyntaxhighlight>
Constants can be initialized with expressions:
<langsyntaxhighlight lang="seed7">const integer: foobar is 2 * length(bar) * (foo - 35);</langsyntaxhighlight>
Any function, even user defined functions can be used to initialize a constant:
<langsyntaxhighlight lang="seed7">const func float: deg2rad (in float: degree) is # User defined function
return degree * PI / 180.0;
 
const float: rightAngle is deg2rad(90.0);</langsyntaxhighlight>
The initialisation expression is evaluated at compile-time.
It is possible to initialize a constant with data from the file system:
<langsyntaxhighlight lang="seed7">const string: fileData is getf("some_file.txt");</langsyntaxhighlight>
The compiler can even get initialisation data from the internet:
<langsyntaxhighlight lang="seed7">const string: unixDict is getHttp("www.puzzlers.org/pub/wordlists/unixdict.txt");</langsyntaxhighlight>
Types are also defined as constants (in other languages this is called a ''typedef''):
<langsyntaxhighlight lang="seed7">const type: blahtype is integer;</langsyntaxhighlight>
Function definitions (see above for the definition of ''deg2rad'') have also the form of a <code>const</code> definition.
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">define PI = 3.14159; # compile-time defined constant
const MSG = "Hello world!"; # run-time defined constant</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<langsyntaxhighlight SuperColliderlang="supercollider">// you can freeze any object.
b = [1, 2, 3];
b[1] = 100; // returns [1, 100, 3]
b.freeze; // make b immutable
b[1] = 2; // throws an error ("Attempted write to immutable object.")</langsyntaxhighlight>
 
=={{header|Swift}}==
Swift has a notion of immutable values built into the language.
<langsyntaxhighlight lang="swift">let a = 1
a = 1 // error: a is immutable
var b = 1
b = 1</langsyntaxhighlight>
 
It also extends this to higher level data structures. For example Swift has a notion of value types vs reference types.
 
<langsyntaxhighlight lang="swift">/// Value types are denoted by `struct`s
struct Point {
var x: Int
Line 1,127 ⟶ 1,420:
 
let pClass = ClassPoint(x: 1, y: 1)
pClass.x = 2 // Fine because reference types can be mutated, as long as you are not replacing the reference</langsyntaxhighlight>
 
Value types are always passed by value. This applies to collections in Swift.
 
<langsyntaxhighlight lang="swift">
// A common Swift beginner trap
func addToArray(_ arr: [Int]) {
Line 1,140 ⟶ 1,433:
let array = [1]
addToArray(array)
print(array) // [1], because value types are pass by copy, array is immutable</langsyntaxhighlight>
 
=={{header|Tcl}}==
Although there is no built-in support for constants, it is trivial to construct on top of Tcl's variable tracing facility:
<langsyntaxhighlight lang="tcl">proc constant {varName {value ""}} {
upvar 1 $varName var
# Allow application of immutability to an existing variable, e.g., a procedure argument
Line 1,153 ⟶ 1,446:
return -code error "immutable"
}} $value]
}</langsyntaxhighlight>
Interactive demonstration:
<langsyntaxhighlight lang="tcl">% constant pi 3.14159
% puts "pi=$pi"
pi=3.14159
Line 1,161 ⟶ 1,454:
can't set "pi": immutable
% puts "pi is still $pi"
pi is still 3.14159</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 1,167 ⟶ 1,460:
 
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="sh">PIE=APPLE
readonly PIE</langsyntaxhighlight>
 
==={{header|C Shell}}===
<langsyntaxhighlight lang="csh">set -r PIE = APPLE</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">define Pi=3.14;
Pi:= 3.15; \causes a compile error: statement starting with a constant
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
In V (Vlang):
 
1) Variables are immutable, by default.
 
2) Structs are immutable, by default.
 
3) Function arguments are immutable, by default.
 
4) Strings are immutable, and you can't mutate elements.
 
To change the values of variables, arguments, and struct fields the keyword "mut" is used.
<syntaxhighlight lang="v (vlang)">// To change the value of the variable, after making it mutable with "mut", use "=".
 
mut age := 20
println(age)
age = 21
println(age)
 
// For structs, we can define whether immutable or mutable by using the "mut" keyword.
// Outside of a function example:
 
struct Point {
mut:
x int
y int
}
// Inside of a function example:
 
mut p := Point{
x: 10
y: 20
}
 
// Function argument example:
 
fn (mut arg Point) register() {
println("Show the struct:\n $arg")
}
 
// V string individual elements are immutable, so we cannot assign to s[i], and will get an error.
 
mut s := 'hello'
s[0] = m // not allowed</syntaxhighlight>
 
=={{header|Wren}}==
In Wren, instance and static fields of a class are always private and cannot be mutated unless you provide 'setter' methods for that purpose.
 
In addition instances of the built-in Num, Bool, String, Range and Null classes are always immutable.
 
Other than this, there is no way to create immutable values (nor constants for that matter) in Wren.
 
The following example shows a simple class A which has a single field _f. Access to this field is controlled by getter and setter methods 'f' and 'f='. Without the setter, instances of A would be effectively immutable.
 
Note though that if fields are reference types (lists, maps, user-defined classes etc.) even a 'getter' method may enable their internal state to be mutated unless you copy them first.
<syntaxhighlight lang="wren">class A {
construct new(f) {
_f = f // sets field _f to the argument f
}
 
// getter property to allow access to _f
f { _f }
 
// setter property to allow _f to be mutated
f=(other) { _f = other }
}
 
var a = A.new(6)
System.print(a.f)
a.f = 8
System.print(a.f)</syntaxhighlight>
 
{{out}}
<pre>
6
8
</pre>
 
{{libheader|Wren-trait}}
Since the above entry was written, a ''Const'' class has been added to ''Wren-trait'' which simulates constants to some extent though the values used need themselves to be immutable for this to be water-tight.
<syntaxhighlight lang="wren">import "./trait" for Const
 
Const["six"] = 6
Const["eight"] = 8
Const["six"] = 7 // ignored, still 6
System.print(Const.entries)</syntaxhighlight>
 
{{out}}
<pre>
[eight:8, six:6]
</pre>
 
=={{header|Z80 Assembly}}==
The Z80 itself has no way of enforcing immutability. Code and/or data are only immutable if they exist in ROM (read-only memory.) Typically, Z80-based computers will copy the contents of a floppy disk or CD-ROM to internal RAM and execute it there, whereas ROM cartridges are directly mapped into the Z80's address space and executed in ROM. As a result, there is no special syntax for enforcing immutability, as it relies entirely on where the code/data is located and what medium it is executed from.
 
Side note: Trying to write to ROM at runtime will simply have no effect, and will not raise any kind of hardware exception or segfault.
 
<syntaxhighlight lang="z80">List:
byte 2,3,4,5,6 ;this could be either mutable or immutable, it depends on the hardware.</syntaxhighlight>
 
=={{header|zkl}}==
Mutability is up to each object. Strings, numbers are immutable. Lists can be either. Dictionaries can switch.
<langsyntaxhighlight lang="zkl">List(1,2,3).del(0) //--> L(2,3)
ROList(1,2,3).del(0) //-->SyntaxError : Can't find del, which means you can't call it
d:=Dictionary(); d.add("one",1)
D(one:1)
d.makeReadOnly(); d.add("2",2) //-->AccessError(This Dictionary is read only)</langsyntaxhighlight>
 
 
{{omit from|AWK| Does not support constants or readonly variables}}
{{omit from|EasyLang|No way to define constants}}
{{omit from|Lily}}
{{omit from|Maxima}}
9,476

edits