The goal is to test how a programming language allows data sharing.

In Various Languages

I = Immutable, D = Deep, S = Shallow, C = Constructor is Constant (see below)
Language integerstringlist/arraystruct/object
C++ I D D D
Perl I D(1) D S
Tcl I D? D? ?
Python I I S S
Java I I S S
Javascript I I S S
C# I I S D/S
Smalltalk I S,C S S
Common Lisp I S,C S S
OCaml I S I/S S
Scheme I S S S
Ruby I S S S
(1) In Perl, "=" deep copies strings, whereas function calls use shallow copy.


Deep vs Shallow Copy

The simplest explanation is an example in C:
Point *p2;
 p2 =  p; // shallow copy
*p2 = *p; // deep copy

char *s2;
s2 = s;        // shallow copy
strcpy(s2, s); // deep copy
When you deep copy a value, it breaks any sharing it has.
When you shallow copy a value, it keeps any sharing it has.

Languages using deep copy by default always have a special way to get a shallow copy:

Languages using shallow copy by default sometimes have a way to get deep copy: copy in Smalltalk, Clone in C#, copy.copy in Python... (more, search "object cloning")

Immutable Value

An example of immutable value is 1. The programming language doesn't give you any functions that would allow you to modify its value.

Deep or shallow copying have the same result for immutable values.

Mutating variables containing an immutable value

Most languages introduce a (more or less magical) construct to modify the value contained by a variable. The usage of is somewhat blurred.


Strings can be mutable or immutable. The current trend is immutable strings (Java, C#, Python) or deep copied mutable strings (Perl, PHP, C++)

Read-only strings

A mutable string can be constant. This is used for constant strings encountered in a program:

In C, Smalltalk and Common Lisp, "hello" is a constant value. If you try to modify it, you get a runtime error.

Ruby and OCaml don't have readonly strings, all strings are mutable:

LanguageCodeRuntime Result
C"hello"[0] = 'H';segmentation fault
Smalltalk'hello' at: 1 put: $Hobject is read-only
Common Lisp(setf (aref "hello" 0) #\H)Attempt to modify a read-only string
Scheme(string-set! "hello" 0 #\H)
OCaml"hello".[0] <- 'H'
Ruby"hello"[0] = "H"
Perl"hello" =~ s/h/H/Can't modify constant item

Mutable Numbers?!

A language that would seek complete orthogonality could treat numbers the same as other objects, i.e. have mutable numbers (Haskell notwithstanding of course). The main reason for having immutable numbers was performance and memory consumption. Maybe this will change?


[1] The address-of operator of Perl and C are different from the "ref" reference constructor of SML and OCaml. In Perl and C, it allows sharing the existing value, whereas ML's "ref" introduces sharing.
int i = 1;
int *p = &i;
*p = *p + 1;
i is modified
let i = 1 in
let p = ref i in
p := !p + 1
i is not modified

[2] To be precise "++" is not defined in Ruby. Some explanation about this.


This document is licensed under GFDL (GNU Free Documentation License).

Release: $Id$