Skip to content

Instantly share code, notes, and snippets.

@aldwyish
Created October 15, 2011 03:39
Show Gist options
  • Select an option

  • Save aldwyish/1288990 to your computer and use it in GitHub Desktop.

Select an option

Save aldwyish/1288990 to your computer and use it in GitHub Desktop.
a demonstration on how to use the solution predicate in Mercury
:- module prime_factor.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list,solutions,int.
%
% small_prime and small_prime_factor taken from
% the tutorial book check page 45
%
:- pred small_prime(int::out) is multi.
small_prime(2).
small_prime(3).
small_prime(5).
small_prime(7).
:- pred small_prime_factor(int::in, int::out) is nondet.
small_prime_factor(X, P) :-
small_prime(P),
X mod P = 0.
main(!IO) :-
% note how we called small_prime_factor with one argument only.
% the solutions predicate is higher order predicate that expect to receive and predicate with one argument
% in output mode :
% solutions(pred(out),list(out)
solutions(small_prime_factor(15),List),
print_list(List,!IO).
%
% print_list and print_list_element taken from the queens example
%
:- pred print_list(list(int)::in, io::di, io::uo) is det.
print_list(Xs, !IO) :-
(
Xs = [],
io.write_string("[]\n", !IO)
;
Xs = [H | T],
io.write_string("[", !IO),
print_list_elements(H, T, !IO),
io.write_string("]\n", !IO)
).
:- pred print_list_elements(int::in, list(int)::in, io::di, io::uo) is det.
print_list_elements(X, Xs, !IO) :-
io.write_int(X, !IO),
(
Xs = []
;
Xs = [H | T],
io.write_string(", ", !IO),
print_list_elements(H, T, !IO)
).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment