I want to create a filter in Prologue from a list that filters out all elements that match the filter.
Example: filter(list, element, result)
?- filter([1,2,3,2,3,1,5],3,X).
X=[3,3]
But I have created a filter that so far only outputs true or false.
filter([L|Y],X,OUT) :- filter(Y,X,OUT).
I don't know how to create a list now.
You actually do not need to implement a filter yourself. There is a filter predicate include/3
[swi-doc] :
filter(L, X, R) :-
, L, R.
You can also implement this yourself with recursion. Here the base case is an empty list:
filter([],_,[]).
for the recursive case, you can make an if-then-else expression that depending on whether the condition is satisfied, make a list that is (not) prepended with that element:
filter([Y|T], X, R) :-
( X == Y
-> …
; …
),
filter(T, X, S).
here you still need to fill in …
yourself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.