Prolog - Palindrome Functor

情到浓时终转凉″ 提交于 2019-12-05 08:41:15

A palindrome list is a list which reads the same backwards, so you can reverse the list to check whether it yields the same list:

palindrome(L):-
  reverse(L, L).

Looks that everybody is voting for a reverse/2 based solution. I guess you guys have a reverse/2 solution in mind that is O(n) of the given list. Something with an accumulator:

 reverse(X,Y) :- reverse(X,[],Y).

 reverse([],X,X).
 reverse([X|Y],Z,T) :- reverse(Y,[X|Z],T).

But there are also other ways to check for a palindrome. I came up with a solution that makes use of DCG. One can use the following rules:

 palin --> [].
 palin --> [_].
 palin --> [Border], palin, [Border].

Which solution is better? Well lets do some little statistics via the profile command of the Prolog system. Here are the results:

So maybe the DCG solution is often faster in the positive case ("radar"), it does not have to build the whole reverse list, but directly moves to the middle and then checks the rest during leaving its own recursion. But disadvantage of DCG solution is that it is non-deterministic. Some time measurements would tell more...

Bye

P.S.: Port statistics done with new plugable debugger of Jekejeke Prolog:
http://www.jekejeke.ch/idatab/doclet/prod/en/docs/10_dev/10_docu/02_reference/04_examples/02_count.html

But other Prolog systems have similar facilities. For more info see, "Code Profiler" column:
http://en.wikipedia.org/wiki/Comparison_of_Prolog_implementations

This sure sounds like a homework question, but I just can't help myself:

palindrome(X) :- reverse(X,X).

Technically, prolog functor don't "return" anything.

Another way, doing it with DCG's:

palindrome --> [_].
palindrome --> [C,C].
palindrome --> [C],palindrome,[C].

You can check for a palindrome like this:

?- phrase(palindrome,[a,b,a,b,a]).
true.

?- phrase(palindrome,[a,b,a,b,b]).
false.

You can use :

palindrome([]).
palindrome([_]).
palindrome([X|Xs]):-append(Xs1,[X],Xs), palindrome(Xs1).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!