code_junkie

Prolog: Filtering a list?

Nov 12th, 2011
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. filter(A, B)
  2.  
  3. filterList(A, [X, Y, Z])
  4.  
  5. filter(_,[],[]).
  6. filter(P, A0-As0, As) :-
  7. (
  8. call(P, A0) -> As = A0-As1
  9. ;
  10. As = As1
  11. )
  12. , filter(P, As0, As1).
  13.  
  14. are_identical(X, Y) :-
  15. X == Y.
  16.  
  17. filterList(A, In, Out) :-
  18. exclude(are_identical(A), In, Out).
  19.  
  20. ?- filterList(A, [A, B, A, C, D, A], Out).
  21. Out = [B, C, D].
  22.  
  23. filterList(_, [], R, R). //Returns answer when the list is exhausted.
  24.  
  25. filterList(L, [A|List], Temp, Res) :-
  26. filterList(L, List, New, Res), //Recursive call, New is either the same list
  27. (filter(L, A), New = Temp; //in case the filter outputs true, or the list
  28. New = [A|Temp]). //plus the current element otherwise.
Add Comment
Please, Sign In to add comment