Hamming Numbers in prolog

Basic testing weather a number is hamming is straightforward. It can be something like this:

hamming(X) :- X =< 0, !, fail.
hamming(1).
hamming(X) :-0 =:= (X mod 2), !, Y is X // 2,  hamming(Y).
hamming(X) :-0 =:= (X mod 3), !, Y is X // 3,  hamming(Y).
hamming(X) :-0 =:= (X mod 5), !, Y is X // 5,  hamming(Y).

But if want to make an ordered list of of all hamming numbers using lazy algorithm, we should try harder.

See this nice site that compares functional and logical languages for a solution.

His solution uses dif predicate to make the evaluation lazy. There are also other predicates for co-routines in Prolog, like freeze.

Prolog’s  freeze/frozen are similar to scheme’s promise/force.

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: