Hash function implementation in Prolog
I am new to 开发者_JAVA技巧Prolog, and I want to know can we implement this in Prolog:
a = hash(first).
And, one who knows first
can calculate a
, but one who knows a
can't calculate first
.
Typicall a hash function is not injective in general. Means that for any value a there is most often a first1 and a first2 such that:
a = hash(first1)
a = hash(first2)
So one cannot say for sure what was the argument to the hash function. But since a hash is supposed to be a small value that can be easily used in search etc., it typically gives some information about the domain of arguments.
If you want a hash where it is difficult to make backward deductions to the argument, you should use a digest. Digest is typically a value generated by some cryptographic algorithm and it is practically infeasible to make deductions about the argument.
I guess the predicates term_hash/2 or so usually found in Prolog systems qualify as hash and not as digest. But you can also implement your own hash function easily. Something along the lines:
my_hash(X,N) :- atom(X), !, atom_codes(X,L), my_hash_codes(L,N).
my_hash(X,N) :- X=..[F|L], my_hash(F,M), my_hash_args(L,R), my_hash_codes([M|R],N).
my_hash_codes([],0).
my_hash_codes([X|Y],N) :- my_hash_codes(Y,M), N is (X+M*31) mod 65531.
my_hash_args([],[]).
my_hash_args([X|Y],[M|N]) :- my_hash(X,M), my_hash_args(Y,N).
The helper predicate my_hash_codes/2 sends a list of numbers to a new number. The helper predicate my_hash_args/2 computes the hash of each list element and builds a new list. The predicate my_hash works for atoms and compounds, but it could be also extended to numbers.
Bye
精彩评论