Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Mercury

Learn Mercury - 10 Code Examples & CST Typing Practice Test

Mercury is a purely declarative logic programming language with strong typing, determinism analysis, and a focus on reliability and performance. It is designed for building large-scale, maintainable, and efficient logic programs while avoiding common pitfalls of traditional Prolog systems.

View all 10 Mercury code examples →
Mercury Counter and Theme ToggleMercury Fibonacci SequenceMercury Factorial CalculatorMercury Prime CheckerMercury Sum of ListMercury Reverse StringMercury Multiplication TableMercury Celsius to FahrenheitMercury Simple Alarm SimulationMercury Random Walk Simulation

Learn MERCURY with Real Code Examples

Updated Nov 20, 2025

Explain

Mercury emphasizes declarative programming, separating logic from control flow.

It provides a strong static type system and mode system for arguments.

Mercury’s compiler optimizes for performance and guarantees no runtime type errors for well-typed programs.

Core Features

Predicates and functions with explicit types

Modes defining input/output arguments

Determinism categories (det, semidet, nondet, multi)

Module system for code organization

Automatic memory management and garbage collection

Basic Concepts Overview

Predicates (relations between terms)

Functions (deterministic computations)

Types (user-defined and built-in)

Modes (input/output specification)

Determinism declarations (det, semidet, multi, nondet)

Project Structure

Source files (.m)

Interface files (.m)

Modules for code organization

Test cases for predicates/functions

Documentation files

Building Workflow

Write Mercury source file with predicates and functions

Specify types, modes, and determinism

Compile using Mercury compiler (mmc)

Test and debug using compiler feedback

Organize code into modules for maintainability

Difficulty Use Cases

Beginner: simple deterministic predicates

Intermediate: multi and nondet predicates

Advanced: large module-based projects

Expert: symbolic computation or constraint systems

Comparisons

Mercury vs Prolog: stronger typing, mode and determinism system, better performance

Mercury vs Haskell: functional vs logic paradigm, Mercury is declarative logic

Mercury vs Python: specialized for logic, smaller ecosystem

Mercury vs Lisp: symbolic computation vs declarative logic

Mercury vs C: higher-level declarative logic, less low-level control

Versioning Timeline

1995 - Mercury project started at University of Melbourne

1998 - First public release

2000s - Compiler optimizations and standard libraries expanded

2010s - Integration with C and Java via FFI improved

2025 - Latest stable release focusing on performance and tooling

Glossary

Predicate: logical relation between terms

Function: deterministic computation

Mode: input/output argument specification

Determinism: guarantees about number of solutions

Module: code organization unit

Installation Setup

Download Mercury compiler for your OS

Install compiler and set PATH environment variable

Verify installation with 'mmc --version'

Create a Mercury source file (.m)

Compile using 'mmc file.m' and run with executable

Environment Setup

Download Mercury compiler

Install compiler and set PATH

Test installation with sample program

Organize source files and modules

Compile and run test predicates

Config Files

Source files (.m)

Interface files (.m)

Makefile or build scripts

Documentation files

Test modules

Cli Commands

mmc --make program.m

mmc --run program

mmc --target=c program.m

mercury --help

mercury --version

Internationalization

Supports Unicode in string terms

Localization handled via program logic

No built-in i18n system

Integration via external libraries possible

Useful for multi-language logic programs

Accessibility

Command-line interface

Mercury compiler available for Linux, macOS, Windows

Documentation and tutorials accessible online

Active research community

IDE support via editors like Emacs, Vim, VSCode

Ui Styling

Mercury does not provide GUI or styling

Typically used for backend logic or symbolic computation

Output via console or external interface

Integration possible via FFI for GUI

Focus on logic correctness over presentation

State Management

Logic state represented by predicates

Input/output managed via modes

Pure declarative approach ensures predictable state

Modules encapsulate local state

Side effects isolated in deterministic code paths

Data Management

Strongly typed terms and structures

Input/output specified via modes

Recursion for data traversal

No mutable state; pure declarative semantics

Use of lists, sets, and user-defined types

Architecture

Declarative logic programming paradigm

Strong typing with compile-time checks

Determinism analysis for predicates

Module-based organization

Optimized native code generation

Rendering Model

Mercury source code

Compiled by Mercury compiler

Predicates and functions executed deterministically

Modules organize code

FFI for integrating with external systems

Architectural Patterns

Declarative logic

Module-based organization

Static typing and mode-checking

Determinism enforcement

Optimized compilation pipeline

Real World Architectures

Knowledge-based systems

Symbolic computation pipelines

Constraint-solving engines

Formal verification tools

Academic research projects

Design Principles

Declarative logic programming

Strong typing and mode analysis

Determinism checking

Separation of logic and control

Optimized compilation for performance

Scalability Guide

Organize large logic programs into modules

Use deterministic predicates when possible

Optimize recursion for large data sets

Test modules independently

Integrate with other systems via FFI efficiently

Migration Guide

Port Prolog projects to Mercury for type safety

Update predicates to include modes and determinism

Refactor code into modules

Compile and test with Mercury compiler

Leverage FFI for external system integration

Performance Notes

Mercury compiler generates optimized native code

Tail recursion improves performance for recursive predicates

Minimize use of nondeterministic predicates when possible

Compiler warnings help detect inefficiencies

Memory management is automatic but can be tuned for large programs

Security Notes

Mercury itself is safe due to declarative semantics

Avoid unsafe foreign function interface (FFI) calls

Validate inputs for critical predicates

Limit external system access in logic programs

Use compiler checks to prevent unexpected runtime errors

Monitoring Analytics

Profile predicate execution

Check memory usage for large logic sets

Analyze recursive calls for efficiency

Use compiler warnings for optimization

Trace deterministic and non-deterministic paths

Code Quality

Strongly typed code with explicit modes

Exhaustive determinism declarations

Modular and maintainable structure

Comment predicates and logic rules

Test small predicates before integration

Practical Examples

Family tree reasoning

Constraint satisfaction problems

Symbolic math computations

Natural language parsing

Rule-based expert systems

Troubleshooting

Check type errors reported by compiler

Verify mode correctness for input/output

Ensure determinism declarations match predicate behavior

Test predicates with sample queries

Refactor code for module organization

Testing Guide

Write deterministic test predicates

Check semidet predicates for success/failure

Use sample queries to validate logic

Debug using compiler messages

Organize test modules for complex programs

Deployment Options

Compile to native executable

Embed in other applications via FFI

Run interactively via Mercury REPL

Distribute as source for academic use

Use in constraint-solving or AI pipelines

Tools Ecosystem

Mercury compiler (mmc)

Mercury REPL for interactive testing

Debugger integrated in compiler

Module system for code organization

Documentation generator (mercury doc)

Integrations

Foreign function interface (C, Java, etc.)

Libraries for constraint solving

Symbolic computation frameworks

Integration with Prolog for legacy code

Academic tools for theorem proving

Productivity Tips

Leverage static types and modes early

Modularize predicates for clarity

Test small logic components incrementally

Use determinism analysis for optimization

Integrate FFI for performance-critical tasks

Challenges

Implement a family tree reasoning system

Build a simple expert system

Write symbolic math solver

Parse natural language phrases

Develop small AI logic module

Learning Path

Learn basic logic programming concepts

Understand types, modes, and determinism

Practice predicate and function definitions

Build small logic modules

Progress to large declarative systems

Skill Improvement Plan

Week 1: Mercury syntax and types

Week 2: Modes and determinism

Week 3: Predicate and function writing

Week 4: Module-based projects

Week 5: Constraint solving and symbolic computation

Interview Questions

What is the difference between Mercury and Prolog?

Explain determinism categories in Mercury

How do modes help in Mercury predicates?

Describe Mercury’s type system

When would you choose Mercury for a project?

Cheat Sheet

:- module family.

:- interface.

:- import_module io.

:- pred parent(string, string).

parent('Alice', 'Bob').

Books

The Mercury Programming Language (Somogyi et al.)

Logic Programming with Mercury

Declarative Programming Techniques

Constraint Solving and Symbolic Computation

Advanced Mercury Programming

Tutorials

Introduction to Mercury Programming

Logic Programming with Mercury

Determinism and Modes in Mercury

Building Symbolic Computation with Mercury

Mercury for Constraint Solving

Official Docs

Mercury Language Reference Manual

Mercury Compiler User Guide

University of Melbourne Mercury Resources

Mercury Tutorials and Examples

Mercury FFI Documentation

Community Links

Mercury mailing lists

University of Melbourne Mercury page

GitHub Mercury projects

Logic programming forums

Research papers using Mercury

Community Support

Mercury mailing lists

University of Melbourne Mercury page

GitHub Mercury projects

Academic papers and tutorials

Logic programming forums

Monetization

Academic research and publications

Symbolic computation consulting

Logic-based software solutions

Educational courses in logic programming

Prototyping AI and constraint systems

Future Roadmap

Enhanced tooling and IDE support

Expanded FFI integration

Improved compiler optimizations

Community-driven library ecosystem growth

Continued use in research and teaching

When Not To Use

Web and mobile application development

Real-time embedded systems

Mainstream commercial software without logic reasoning

Large-scale GUI applications

Performance-critical numeric computing outside logic domain

Final Summary

Mercury is a strongly typed, purely declarative logic programming language for building reliable, maintainable logic programs.

It combines type, mode, and determinism analysis with high-performance compilation.

Ideal for research, symbolic computation, and complex logic systems.

Faq

Is Mercury still in use?

Yes, primarily in research and education.

Can Mercury integrate with C?

Yes, via Foreign Function Interface (FFI).

Is Mercury purely functional?

It is purely declarative logic-based, not functional in the Haskell sense.

Why learn Mercury?

To build reliable logic-based programs and understand advanced logic programming concepts.

Code Sample Descriptions

1

Mercury Counter and Theme Toggle

:- module counter.
:- interface.
:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    Count = 0,
    IsDark = no,
    updateUI(Count, IsDark, !IO),
    Count1 = Count + 1,
    updateUI(Count1, IsDark, !IO),
    Count2 = Count1 + 1,
    updateUI(Count2, IsDark, !IO),
    IsDark1 = yes,
    updateUI(Count2, IsDark1, !IO),
    Count3 = Count2 - 1,
    updateUI(Count3, IsDark1, !IO),
    Count4 = 0,
    updateUI(Count4, IsDark1, !IO).

:- pred updateUI(int::in, bool::in, io::di, io::uo) is det.
updateUI(Count, IsDark, !IO) :-
    io.write_string("Counter: "), io.write_int(Count), io.write_string("\n", !IO),
    (io.write_string("Theme: Dark\n", !IO) :- IsDark ; io.write_string("Theme: Light\n", !IO)).

Demonstrates a simple counter with theme toggling using Mercury predicates and declarative constructs.

Let’s Try →
2

Mercury Fibonacci Sequence

:- module fib.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- func fib(int) = int.
fib(N) = (if N =< 1 then N else fib(N-1) + fib(N-2)).

main(!IO) :-
    for I = 0 to 9 do io.write_int(fib(I), !IO), io.write_string("\n", !IO).

Generates first 10 Fibonacci numbers using a pure predicate.

Let’s Try →
3

Mercury Factorial Calculator

:- module factorial.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- func fact(int) = int.
fact(0) = 1.
fact(N) = N * fact(N-1).

main(!IO) :- io.write_int(fact(5), !IO), io.write_string("\n", !IO).

Calculates factorial using a pure function.

Let’s Try →
4

Mercury Prime Checker

:- module prime.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- func is_prime(int) = bool.
is_prime(N) = (if N < 2 then no else not any([X :- X = 2..N-1, N mod X = 0]) ).

main(!IO) :- io.write_string(if is_prime(13) then "Prime\n" else "Not Prime\n", !IO).

Checks if a number is prime.

Let’s Try →
5

Mercury Sum of List

:- module sumlist.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- func sum(list(int)) = int.
sum([]) = 0.
sum([H|T]) = H + sum(T).

main(!IO) :- io.write_int(sum([1,2,3,4,5]), !IO), io.write_string("\n", !IO).

Calculates the sum of a list using a fold.

Let’s Try →
6

Mercury Reverse String

:- module revstring.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- func reverse(list(T)) = list(T).
reverse([]) = [].
reverse([H|T]) = reverse(T) ++ [H].

main(!IO) :-
    L = ['H','E','L','L','O'],
    R = reverse(L),
    io.write_string(R, !IO), io.write_string("\n", !IO).

Reverses a string represented as a list of characters.

Let’s Try →
7

Mercury Multiplication Table

:- module multable.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    N = 5,
    for I = 1 to 10 do
        io.write_int(N, !IO), io.write_string(" x ", !IO), io.write_int(I, !IO), io.write_string(" = ", !IO), io.write_int(N*I, !IO), io.write_string("\n", !IO).

Prints multiplication table for a number.

Let’s Try →
8

Mercury Celsius to Fahrenheit

:- module tempconv.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    C = 25.0,
    F = C * 9.0/5.0 + 32.0,
    io.write_float(F, !IO), io.write_string("\n", !IO).

Converts Celsius to Fahrenheit.

Let’s Try →
9

Mercury Simple Alarm Simulation

:- module alarm.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    Temp = 80,
    Thresh = 75,
    io.write_string(if Temp > Thresh then "Alarm: Temperature Too High!\n" else "Temperature Normal\n", !IO).

Simulates an alarm if threshold exceeded.

Let’s Try →
10

Mercury Random Walk Simulation

:- module randwalk.
:- interface.
:- import_module io, random.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    Steps = 10,
    Pos = 0,
    for I = 1 to Steps do (
        Pos = Pos + (if random(0,1) = 0 then -1 else 1),
        io.write_int(Pos, !IO), io.write_string("\n", !IO)
    ).

Simulates a 1D random walk.

Let’s Try →

Frequently Asked Questions about Mercury

What is Mercury?

Mercury is a purely declarative logic programming language with strong typing, determinism analysis, and a focus on reliability and performance. It is designed for building large-scale, maintainable, and efficient logic programs while avoiding common pitfalls of traditional Prolog systems.

What are the primary use cases for Mercury?

Logic-based and symbolic programming. Constraint solving. Knowledge representation. Formal verification and theorem proving. Academic research and teaching

What are the strengths of Mercury?

Eliminates many runtime errors via type and mode checking. Predictable declarative behavior. Efficient execution through optimized compilation. Highly maintainable large logic programs. Facilitates reasoning about program correctness

What are the limitations of Mercury?

Smaller ecosystem and community. Steeper learning curve than Prolog for beginners. Limited libraries for modern software development. Not suitable for mainstream web or mobile apps. Requires strict adherence to modes and types

How can I practice Mercury typing speed?

CodeSpeedTest offers 10+ real Mercury code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.