Mercury
Mercury, developed at the University of Melbourne in the 1990s, keeps the declarative logic of Prolog but adds what large programs need: a strong static type system, declared modes for arguments and a determinism analysis. The compiler checks all of it, so many bugs never run.
Paradigm: Logic Programming
What Makes Mercury Special
- Static types. Every predicate declares its argument types, such as
list(int). Type errors are found at compile time, not after a failed query. - Modes. A declaration like
io::di, io::uosays which arguments are inputs and which are outputs. The compiler orders goals accordingly. - Determinism categories. Each predicate is
det(exactly one answer),semidet(zero or one),multi(one or more) ornondet. The compiler proves it. - Pure I/O through state variables. I/O is threaded as
!IO, which lets the language stay declarative and still print. - Much faster than Prolog. Because types, modes and determinism are known, the compiler generates efficient code without backtracking overhead.
Example: Summing a list with declared determinism
:- module sum_list.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list.
:- func sum(list(int)) = int.
sum([]) = 0.
sum([X | Xs]) = X + sum(Xs).
main(!IO) :-
io.write_int(sum([1, 2, 3, 4]), !IO),
io.nl(!IO).
How It Works
- The
interfaceexports onlymain; everything underimplementationis private to the module. :- pred main(io::di, io::uo) is det.states thatmaintakes the I/O state as input and returns a new one, and always succeeds exactly once.sumis written as a function, a Mercury feature that sugars the equivalent predicate. It is defined by two clauses, one for the empty list.!IOis shorthand for a pair of state variables, so the two calls are ordered without writing the intermediate names. The program prints10.
History and Where It Is Used
Mercury is used in research, compilers and industrial systems where correctness and performance both matter (the Prince XML formatter is written in it). It is a good way to study how types and modes can make logic programming reliable. The Mercury compiler is free and open source.
Learn More
- Mercury home page
- Mercury (Wikipedia)
- Back to Logic Programming or the PGP roadmap.