Mocktheduck
Mocktheduck

Reputation: 1423

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?

Upvotes: 2

Views: 4745

Answers (1)

Enigmativity
Enigmativity

Reputation: 117124

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

Upvotes: 6

Related Questions