Implementing Select/3 in Prolog

I'm new to Prolog and came across this predicate, select/3. I figured how it works though I'm uncertain how I would implement it myself. I think something like:

selec(El,[El|T],T).
selec(El,[H|T],[H|S]) :-
      selec(El,T,S).
select(El,[],[]).

I know something is wrong. My solution only removes the first occurrence. I want it to remove, all occurrences at some point, just like select/3 does. Any ideas?

5

1 Answer

Your code is perfectly fine, except you don't need the select(El,[],[]). predicate.

This is all you need:

selec(El,[El|T],T).
selec(El,[H|T],[H|S]) :-
      selec(El,T,S).

Do keep in mind that the standard prolog parameter order is inputs followed by outputs, so you really should write it like this:

selec([El|T],El,T).
selec([H|T],El,[H|S]) :-
      selec(T,El,S).
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest