Finding the predecessor / successor of a list item in Prolog -
i having hard time translating idea lisp prolog. did find out how find predecessor , successor in lisp having hard time implementing same idea in prolog. poor syntax. please me out.
sample queries:
?- predecessor(b,[a,b,c],p). p = a. % expected result ?- successor(b,[a,b,c],s). s = c. % expected result
here's dcg approach:
pred(x, p) --> stuff, [p,x], stuff. succ(x, s) --> stuff, [x,s], stuff. stuff --> [] | [_], stuff. predecessor(x, l, p) :- phrase(pred(x, p), l). successor(x, l, p) :- phrase(succ(x, s), l).
sporadic trials:
| ?- predecessor(a, [a,1,2,a,3], l). l = 2 ? ; no | ?- predecessor(x, [1,2,3,2,5], 2). x = 3 ? x = 5 no | ?- successor(a, [a,1,2,a,3], l). l = 1 ? l = 3 no | ?- successor(x, [1,2,3,2,5], 2). x = 1 ? x = 3 no | ?-
per @false's comments, implementation can tidied bit:
predecessor(x, l, p) :- phrase((..., [p,x], ...), l). successor(x, l, s) :- phrase((..., [x,s], ...), l). ... --> [] | [_], ... .
with same test results.
Comments
Post a Comment