list - Prolog removing all variables and duplicates -
i need query, remove me variables , duplicates list.
example:
?- l = [1,2,3,x,y,3,2], my_awesome_predicate(l, res).
then, res should be: [1,2,3].
i don't care order (it [2,3,1], [3,2,1] or whatever).
unfortunately, have task in have care efficiency, main question - can done faster? currently, have following code:
remove_variables([], []). remove_variables([h|list], res):- var(h), !, remove_variables(list, res). remove_variables([h|list], [h|res]):- remove_variables(list, res). my_awesome_predicate([], []). my_awesome_predicate(list, res):- sort(list, sorted), remove_variables(sorted, res).
if using swi can improve little further code:
my_awesome_predicate(list, res):- sort(list, mres), remove_variables(mres, res). remove_variables([var|tail], ntail):- var(var), !, remove_variables(tail, ntail). remove_variables(res, res).
as seems swi's sort leave unbounded variables first (don't know if behavior standard among other prolog's), can stop removing variables once find first non-variable.
reading bit swi's documentation, it's stated that:
4.7.1 standard order of terms comparison , unification of arbitrary terms. terms ordered in called ``standard order''. order defined follows: 1. variables < numbers < atoms < strings < compound terms
so seems safe stop removing elements when find first non-variable...
Comments
Post a Comment