Search code examples
listprolog

How to get prime numbers from list and put them in empty list


I want to get all prime numbers from a list of numbers and put it into another empty list. My problem is that whenever the function isPrime is false, the program is terminated. I'm very beginner in prolog, so if you have any feedback I'll appreciate the help. Here is my code below:

check_prime(X):-
     Xtemp is integer(X/2),
     isPrime(X,Xtemp).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
isPrime(_,2).
isPrime(2,_).
isPrime(Num,Counter):-
     X is Counter-1,
     X \= 0,
     X2 is mod(Num,X),
     X2 \= 0,
     isPrime(Num,X).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
prime_list([],Y).
prime_list([H|T],[H|T2]):-
     check_prime(H),
     prime_list(T,T2).

Solution

  • Your check_prime function will give true even for non-prime numbers. Example: check_prime(4) will call isPrime(4, 2), which will unify with the first clause of isPrime.

    An example of code that gives you the list of primes would be this:

    % predicate to check if X has any divisors
    divisible(X,Y) :- 0 is X mod Y, !.
    divisible(X,Y) :- X > Y+1, divisible(X, Y+1).
    
    %predicate to check if that number is prime by using the divisible predicate
    isPrime(2) :- true,!.
    isPrime(X) :- X < 2,!,false.
    isPrime(X) :- not(divisible(X, 2)).
    
    %predicate that returns the resulted list
    primeList([], []). % stopping condition, when list empty
    % we add current element to the resulting list if it is prime 
    primeList([H|T], [H|R]):- isPrime(H), !, primeList(T, R). 
    % otherwise, we just skip it
    primeList([_|T], R):- primeList(T, R). 
    

    Query: ?-primeList([1,2,3,4,5,6,7,8,9], R). => R=[2,3,5,7]