sitelogo
tv_get/3

Retrieves the ith term in a term vector.

tv_get(+Vector, +Index, ?Term)

tv_get/3 retrieves a copy of the term at index Index in the term vector Vector and unifies it with Term. Index has to be an integer in the range 1 .. N, where N is the size of the term vector (see tv_size/2).

Arguments

Vector                  object (term vector)
Index                   integer
Term                    term

Examples

% find all prime numbers between 1 and N
prime_sieve(N, Primes) :-
    % create a term vector
    tv_create(Vector),
    % set it's size to N and fill all elements to 'prime'
    init_sieve(Vector, N),
    % set all non prime numbers to 'not_prime'
    compute_primes(Vector, N),
    % collect all elements still marked with 'prime'
    collect_primes(Vector, N, Primes).

init_sieve(Vector, N) :- % set the vector size to N tv_setsize(Vector, N), % set all vector elements to 'prime' for(1, I, N), tv_set(Vector, I, prime), fail. init_sieve(_, _).

compute_primes(Vector, N) :- for(2, I, N), % if I is still marked as prime ... tv_get(Vector, I, prime), % ... mark all multiples of I as 'not_prime' filter_primes(Vector, I, I, N), fail. compute_primes(_, _).

filter_primes(Vector, I, Step, N) :- J is I+Step, J =< N, !, % mark all multiples of 'Step' as 'not_prime' tv_set(Vector, J, not_prime), filter_primes(Vector, J, Step, N). filter_primes(_, _, _, _).

collect_primes(Vector, N, Primes) :- % collect all elements still marked as 'prime' findall(I, isprime(Vector,I,N), Primes).

isprime(Vector, I, N) :- for(1,I,N), tv_get(Vector,I,prime).

Standard

This predicate is not part of the ISO-Prolog Standard.

See also

tv_create/1, tv_add/2, tv_size/2, tv_setsize/2, tv_set/3, tv_get/3, tv_list/2.


Up read on...
scroll to top managed with ubiCMS