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...
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?
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).