[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
## Re: AW: function hash for prolog terms?

**From**: |
Daniel Diaz |

**Subject**: |
Re: AW: function hash for prolog terms? |

**Date**: |
Wed, 11 Feb 2004 23:43:12 +0100 |

**User-agent**: |
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113 |

Hi,

`You'll find as an attachment another Prolog solution to compute a hash
``code from a term.
`

Hello,
I am working using the interface of GNU-Prolog for C.
I need a function that returns me an unique number for each
prolog term. Up
to now I am using the following one
int hash(PlTerm termino_prolog) {
return abs (Rd_Code (termino_prolog));
}
But there are cases in those that it stops oneself prolog term it
returns me
different values.
Thank you for your help.

Daniel,
while I don't know about the semantics of "Rd_Code", I suspect, that the
returned information might be not unique to a specific term.
For a true hash you need a guaranteed unique function however.
So I would suggest, that you implement it as follows:
term_hash(Term,Hash) :-
write_canonical_to_atom(CanonicalAtom,Term),
my_md5_digest(CanonicalAtom,Hash).
Of course, this would involve an implementation of "my_md5_digest".
You can easily wrap a "stock" MD5 function, written in C, to perform this
task.
HTH
Regards
Ingo

term_hash(T, H) :-
term_hash1(T, H0),
H is H0 /\ 268435455 .
term_hash1(X, _) :-
var(X), !,
throw(error(instantiation_error, term_hash / 2)).
term_hash1(X, H) :-
atom(X), !,
atom_hash(X, H).
term_hash1(X, H) :-
integer(X), !,
H = X.
term_hash1(X, H) :-
float(X), !,
H is round(float_fractional_part(X) * 100000) \/
round(float_integer_part(X)).
term_hash1(T, H) :-
functor(T, F, N),
atom_hash(F, H0),
term_hash2(0, N, T, 0, H1),
H is H1 * 129 + H0.
term_hash2(I, N, T, H0, H) :-
( I = N ->
H = H0
; I1 is I + 1,
arg(I1, T, A),
term_hash1(A, H1),
H2 is H0 * 129 + H1,
term_hash2(I1, N, T, H2, H)
).