'prolog filter/3 predicate never shows output
I want to create a predicate filter/3 or filter(Condition,List,Solution) that checks every element of the list and if returns true in the condition put it in the Solution list. How can I do this?
This is my code:
%% less_ten/1
%% less_ten(X)
less_ten(X) :- X < 10.
%% less_twenty/1
%% less_twenty(X)
less_twenty(X) :- X < 20.
%% filter/3
%% filter(C,List,Solution)
filter(_,[],Solution).
filter(C,[Head|Tail],Solution) :-
(
Predicate=..[C,Head],
call(Predicate),
!,
append(Solution,Head,NewSolution),
filter(C,Tail,NewSolution)
);
(
filter(C,Tail,Solution)
).
Solution 1:[1]
Seems like all you need is
filter( [] , _ , [] ) .
filter( [X|Xs] , P , [X|Ys] ) :- call(P,X), !, filter(Xs,P,Ys) .
filter( [_|Xs] , P , Ys ) :- filter(Xs,P,Ys) .
The reason for putting the source list before the test predicate is that first argument indexing can improve execution speed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nicholas Carey |