Maybe, Either and exceptions: Haskell and C++
A function that turns text into a number can fail, and the failure is the interesting half of its type. C++ has three answers in the standard library: a status plus an out parameter, the class of the function, std::optional for the absence of a value and, since C++23, std::expected for a value or an error. Haskell has two: Maybe for absence and Either e for a reason.
The programs below parse the same two strings, "42" and "4x", and print the same four lines. Then the page shows where the two languages part: what the type makes a caller do, and what happens at run time when nobody does it.
optional, expected and try
std::stoi parses a prefix and reports how many characters it used, and it throws for a string that has no number at all. parse_optional wraps it in a try and returns nullopt for both failures, so the caller has one case to handle instead of two. parse_expected returns the reason with the failure, which is the type a program needs when the message is shown to a user.
#include <cstdio>
#include <expected>
#include <optional>
#include <stdexcept>
#include <string>
std::optional<int> parse_optional(const std::string& text) {
try {
std::size_t used = 0;
const int value = std::stoi(text, &used);
if (used != text.size()) {
return std::nullopt;
}
return value;
} catch (const std::invalid_argument&) {
return std::nullopt;
} catch (const std::out_of_range&) {
return std::nullopt;
}
}
std::expected<int, std::string> parse_expected(const std::string& text) {
try {
std::size_t used = 0;
const int value = std::stoi(text, &used);
if (used != text.size()) {
return std::unexpected("not a number: " + text);
}
return value;
} catch (const std::exception&) {
return std::unexpected("not a number: " + text);
}
}
int main() {
const auto maybe = parse_optional("42");
std::printf("optional 42 -> %d\n", maybe.value_or(-1));
std::printf("optional 4x -> %s\n", parse_optional("4x").has_value() ? "a value" : "nothing");
const auto good = parse_expected("42");
std::printf("expected 42 -> %d\n", good.value());
const auto bad = parse_expected("4x");
std::printf("expected 4x -> %s\n", bad.error().c_str());
}
The build is clean under -Wall -Wextra. The four lines are the two functions on the two inputs:
g++ -std=c++23 -Wall -Wextra -O2 errors.cpp -o errors
./errors; echo "status $?"
optional 42 -> 42
optional 4x -> nothing
expected 42 -> 42
expected 4x -> not a number: 4x
status 0
Maybe and Either
readMaybe from Text.Read is the total version of read: it returns a Maybe instead of dying, and it accepts nothing but the whole string, so "4x" is a Nothing here and a 4 in C++. Either String Int carries the message the C++ expected carries.
The validation at the end takes two fields and collects every error instead of the first. That is not what the Applicative instance of Either does: it stops at the first Left. The collection here is explicit, with partitionEithers over a list of the two results, which is the honest way to do it with the libraries in this image.
module Main (main) where
import Data.Either (partitionEithers)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
import Text.Read (readMaybe)
parseMaybe :: String -> Maybe Int
parseMaybe = readMaybe
parseEither :: String -> Either String Int
parseEither text =
case readMaybe text of
Just value -> Right value
Nothing -> Left ("not a number: " ++ text)
data Row = Row Int Int
deriving (Show)
field :: String -> String -> Either String Int
field name text =
case readMaybe text of
Just value -> Right value
Nothing -> Left ("not a number in " ++ name ++ ": " ++ text)
validate :: String -> String -> Either [String] Row
validate left right =
case partitionEithers [field "left" left, field "right" right] of
([], [first, second]) -> Right (Row first second)
(errors, _) -> Left errors
main :: IO ()
main = do
printf "optional 42 -> %d\n" (fromMaybe (-1) (parseMaybe "42"))
putStrLn ("optional 4x -> " ++ maybe "nothing" (const "a value") (parseMaybe "4x"))
case parseEither "42" of
Right value -> printf "expected 42 -> %d\n" value
Left message -> putStrLn ("expected 42 -> " ++ message)
case parseEither "4x" of
Right value -> printf "expected 4x -> %d\n" value
Left message -> putStrLn ("expected 4x -> " ++ message)
print (validate "42" "7")
print (validate "4x" "7y")
ghc -Wall -O1 -o errors-hs Errors.hs
./errors-hs; echo "status $?"
[1 of 2] Compiling Main ( Errors.hs, Errors.o )
[2 of 2] Linking errors-hs
optional 42 -> 42
optional 4x -> nothing
expected 42 -> 42
expected 4x -> not a number: 4x
Right (Row 42 7)
Left ["not a number in left: 4x","not a number in right: 7y"]
status 0
An error in the type
parseEither :: String -> Either String Int is a promise a caller can read and a compiler can enforce. A Maybe Int is not an Int: the only way to get one out is to handle both constructors, and a case that forgets Nothing is a warning under -Wall. There is a way around it, fromMaybe with a default, and that is a decision the caller writes down.
A C++ function that throws says nothing in its signature. A caller who does not read the documentation does not know the call can fail, and std::optional and std::expected fix that by moving the failure into the return type, exactly as Haskell does. The difference that remains is the default: a C++ program written in the old style throws, and the type system does not notice. noexcept and -fno-exceptions are the knobs that turn that around, and both are per function and per build.
The cost of the two styles differs where the failure is rare. An exception that is thrown is slow, because it walks the stack and unwinds it; an exception that is caught in the happy path costs nothing on the compilers that use table-driven unwinding. A Maybe or an expected costs a branch per call and is paid whether the failure happens or not. For a parser called a million times the branch is the better trade; for a constructor that fails once at startup the exception is.
C++ exceptions and Haskell exceptions meet in one place: both can escape through code that does not mention them. Haskell keeps that out of pure code, where the only exceptions are the ones the runtime raises (error, a partial pattern, a division by zero), and the course lesson on exceptions shows try, evaluate and bracket for the IO side.
The prefix, the terminate and the read
The first mistake is silent and it is in the standard library. std::stoi parses as much as it can and stops at the first character that cannot continue the number. It does not care what comes after, so "4x" is four:
#include <cstdio>
#include <string>
int main() {
const std::string text = "4x";
const int value = std::stoi(text);
std::printf("%d\n", value);
}
g++ -std=c++23 -Wall -Wextra -O2 prefix.cpp -o prefix
./prefix; echo "status $?"
4
status 0
That is why both functions in the first program check used != text.size(). Without the check a record with a typo in a numeric field is accepted with a truncated value, and the report at the end is wrong for a reason nobody can find.
The second mistake is a string with no number in it at all and no try around the call. The exception leaves main, nothing catches it, and the runtime calls std::terminate:
#include <cstdio>
#include <string>
int main() {
const std::string text = "four";
const int value = std::stoi(text);
std::printf("%d\n", value);
}
g++ -std=c++23 -Wall -Wextra -O2 uncaught.cpp -o uncaught
./uncaught; echo "status $?"
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
status 134
The status is 134 because the process died by SIGABRT, and the message goes to standard error. A C++ program that lets an exception out of main has no better ending available: there is nobody left to handle it.
The Haskell version of the same call is read, the partial function readMaybe exists to replace. It requires the whole string and it raises an error when the string is not a number:
module Main (main) where
main :: IO ()
main = print (read "4x" :: Int)
ghc -Wall -O1 -o partial-hs Partial.hs
./partial-hs; echo "status $?"
[1 of 2] Compiling Main ( Partial.hs, Partial.o )
[2 of 2] Linking partial-hs
partial-hs: Prelude.read: no parse
status 1
The difference is not that Haskell has no partial functions; it has them, and this one is in the Prelude. The difference is that the partial function returns an Int, so its type says nothing about the failure, and a reader who wants to be sure reaches for readMaybe. In C++ the same decision is called std::stoi or std::from_chars, and only one of them tells you where it stopped.
The Haskell lesson on the subject is Either and recoverable errors, and the next page in this set is Strings, Text and ByteString against std::string.
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