especially aggregate , help to use non-determinism:
remove_longest(Pred, L, R) :-
aggregate(max(C,Xc/Yc), P^(append([Xc,P,Yc],L), maplist(Pred,P), length(P,C)), max(C,X/Y)),
append(X, Y, R).
the predicate (is_prime for your case) remains general. In this run example, I use only the atom identity of 'a':
?- remove_longest(=(a), [1,2,3,a,a,4,5,a], R).
R = [1, 2, 3, 4, 5, a].
source
share