Recursive Prolog predicate for reverse / palindrome

前端 未结 4 2116
北荒
北荒 2020-12-03 21:59
  1. Can I get a recursive Prolog predicate having two arguments, called reverse, which returns the inverse of a list:

    Sample query and expected result:

4条回答
  •  被撕碎了的回忆
    2020-12-03 22:42

    Just for curiosity here goes a recursive implementation of reverse/2 that does not use auxiliary predicates and still reverses the list. You might consider it cheating as it uses reverse/2 using lists and the structure -/2 as arguments.

    reverse([], []):-!.
    reverse([], R-R).
    reverse(R-[], R):-!.
    reverse(R-NR, R-NR).
    reverse([Head|Tail], Reversed):-
      reverse(Tail, R-[Head|NR]),
      reverse(R-NR, Reversed).
    

提交回复
热议问题