Skip to content

Instantly share code, notes, and snippets.

@FlyingJester
Created May 22, 2015 19:58
Show Gist options
  • Select an option

  • Save FlyingJester/6621d22b72713f136483 to your computer and use it in GitHub Desktop.

Select an option

Save FlyingJester/6621d22b72713f136483 to your computer and use it in GitHub Desktop.
Example
:- module numberizer.
:- interface.
:- type numberizer.number_type ---> prime ; even ; other.
:- func numberizer.categorize(int::in) = (numberizer.number_type::out) is det.
:- pred numberizer.prime(int::in) is semidet.
:- pred numberizer.even(int::in) is semidet.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int.
% Just for example. Don't worry about a better way to define primes, that's
% not what I'm working on. For the example, 2 is not included since it is
% also even.
numberizer.prime(3).
numberizer.prime(5).
numberizer.prime(7).
numberizer.prime(11).
numberizer.prime(13).
numberizer.prime(17).
numberizer.prime(19).
numberizer.prime(23).
numberizer.even(N::in) :-
N rem 2 = 0.
% THIS. This is the kind of function I want to write.
% Is there a better way to categorize values than this?
% Assume that the type had more possibilities, this would
% end up being a large number of nested if/then/else's.
% Is there a better way? Is the idea of having sorting
% predicates like prime and even actually not a good idea?
numberizer.categorize(N::in) = (Type::out) :-
( if numberizer.prime(N)
then Type = prime
else
( if numberizer.even(N)
then Type = even
else Type = other
)
).
:- pred test_numbers(int::in, int::in, io::di, io::uo) is det.
:- pred test_numbers(int::in, io::di, io::uo) is det.
test_numbers(Max, !IO) :-
test_numbers(Max, 0, !IO).
test_numbers(Max, In, !IO) :-
io.write_int(In, !IO),
numberizer.categorize(In) = Type,
(
Type = prime,
io.write_string(" is prime\n", !IO)
;
Type = even,
io.write_string(" is even\n", !IO)
;
Type = other,
io.write_string(" is not even or prime\n", !IO)
),
( if In < Max
then test_numbers(Max, In+1, !IO)
else io.write_string("", !IO)
).
main(!IO) :-
test_numbers(25, !IO).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment