Immutability and pure functions: Haskell and C++
A program that keeps three versions of one value is the smallest test of a language's idea of state. C++ changes an object and keeps a history by copying it before each change. Haskell has no way to change a value: a function that updates a record returns a new record, and the old one is still there, unchanged, for as long as anybody refers to it.
Both programs below build the same three states of one account and print them in the same format. The output is identical. What differs is the code a reader has to follow to be sure of that, and what the compiler says about an update that was written and then dropped.
A record that changes
The class holds an owner and a balance, and deposit changes the balance in place. To keep the earlier states the program copies the object before each step, which is cheap here and is the copy that value semantics promises: Account after = start; is a new object with its own string.
#include <cstdio>
#include <string>
#include <utility>
class Account {
public:
Account(std::string owner, long balance) : owner_(std::move(owner)), balance_(balance) {}
const std::string& owner() const { return owner_; }
long balance() const { return balance_; }
void deposit(long amount) { balance_ += amount; }
private:
std::string owner_;
long balance_;
};
void print(const char* label, const Account& account) {
std::printf("%-6s %s %ld\n", label, account.owner().c_str(), account.balance());
}
int main() {
Account start("ada", 100);
Account after = start;
after.deposit(10);
Account final = after;
final.deposit(50);
print("start", start);
print("after", after);
print("final", final);
}
The accessors are const so the printer can take a const Account& and the compiler checks that it does not change anything. The build prints nothing and the three states are what the copies captured:
g++ -std=c++23 -Wall -Wextra -O2 account.cpp -o account
./account; echo "status $?"
start ada 100
after ada 110
final ada 160
status 0
A value that is replaced
The Haskell record has the same two fields, and deposit takes the amount and the account and returns an account. The update syntax account {balance = ...} builds a new record with one field changed and the rest shared, so the three names below are three values and the first one cannot change when the second is computed.
module Main (main) where
import Text.Printf (printf)
data Account = Account
{ owner :: String
, balance :: Int
}
deposit :: Int -> Account -> Account
deposit amount account = account {balance = balance account + amount}
printAccount :: String -> Account -> IO ()
printAccount label account = printf "%-6s %s %d\n" label (owner account) (balance account)
main :: IO ()
main = do
let start = Account {owner = "ada", balance = 100}
after = deposit 10 start
final = deposit 50 after
printAccount "start" start
printAccount "after" after
printAccount "final" final
ghc -Wall -O1 -o accounts-hs Accounts.hs
./accounts-hs; echo "status $?"
[1 of 2] Compiling Main ( Accounts.hs, Accounts.o )
[2 of 2] Linking accounts-hs
start ada 100
after ada 110
final ada 160
status 0
What each lets you reason about
In the Haskell version deposit 10 start is a function call and nothing else: it cannot reach into start, cannot read a global, cannot print, because its type has no IO in it. A reader who wants to know what after is looks at one expression. That is what purity buys, and it is the property that makes the three lines of the output provable rather than plausible.
C++ can be written the same way, and a good C++ codebase largely is: const on every accessor, const& on every parameter that is not changed, classes that return a new value instead of mutating. The difference is that it is a convention a reviewer enforces, while in Haskell it is the only thing the language offers. The compiler helps in both cases, and it helps more in one.
The cost is real and goes the other way. A Haskell record update allocates a new record and copies the pointer to the string, so a loop that updates a record a million times allocates a million records unless the strictness of the fields keeps up; the course lesson on seq, $! and bang patterns is about exactly that. C++ mutates one object in place and allocates nothing. Immutability is a trade of allocation for reasoning, and a hot loop is where the trade is paid.
Threads are the other place it shows. The three Haskell values can be read by any number of threads at once, because nothing writes them; the C++ object needs a lock or an atomic as soon as two threads touch it, which is what the page on STM and mutexes measures.
The copy that looks like an update
The mistake C++ lets through is a function that takes the account by value and updates the copy. The call is legal, the parameter is legal, and the object of the caller is untouched. Nothing warns, because the compiler cannot know whether the copy was intended:
#include <cstdio>
#include <string>
#include <utility>
class Account {
public:
Account(std::string owner, long balance) : owner_(std::move(owner)), balance_(balance) {}
const std::string& owner() const { return owner_; }
long balance() const { return balance_; }
void deposit(long amount) { balance_ += amount; }
private:
std::string owner_;
long balance_;
};
void add_bonus(Account account) {
account.deposit(10);
}
int main() {
Account account("ada", 100);
add_bonus(account);
std::printf("%s %ld\n", account.owner().c_str(), account.balance());
}
g++ -std=c++23 -Wall -Wextra -O2 copybug.cpp -o copybug
./copybug; echo "status $?"
ada 100
status 0
The same mistake in Haskell is an update whose result nobody uses. Here the binding updated is computed and then ignored, and the program prints the old balance, exactly like the C++ one:
module Main (main) where
import Text.Printf (printf)
data Account = Account
{ owner :: String
, balance :: Int
}
deposit :: Int -> Account -> Account
deposit amount account = account {balance = balance account + amount}
main :: IO ()
main = do
let account = Account {owner = "ada", balance = 100}
updated = deposit 10 account
printf "%s %d\n" (owner account) (balance account)
ghc -Wall -O1 -o unused-hs Unused.hs
./unused-hs; echo "status $?"
[1 of 2] Compiling Main ( Unused.hs, Unused.o )
Unused.hs:16:9: warning: [GHC-40910] [-Wunused-local-binds]
Defined but not used: ‘updated’
|
16 | updated = deposit 10 account
| ^^^^^^^
[2 of 2] Linking unused-hs
ada 100
status 0
GHC-40910 names the binding and its line: the compiler sees that a pure value was built and never used, which is always a mistake and never a side effect. C++ has the same information and no warning for it, because the parameter of a function is allowed to be a copy. A static analyser such as clang-tidy can be configured to look for the by-value parameter that is modified and discarded, and that is the honest comparison: the check exists on both sides, and only one of them runs it by default.
The Haskell lesson for the record syntax is records, and the next page in this set is Laziness and eager evaluation.
The C++ program was built with g++ 15.2.0 (Alpine 15.2.0) using -std=c++23 -Wall -Wextra -O2 and the Haskell program with GHC 9.10.3 using -Wall -O1, both run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev