All substrings with the same start and end values

I need to solve homework, but I have very limited knowledge of Prolog. The task is as follows:
Write a Prolog program that can list all the substrings of a string whose length is at least two characters, and the first and last characters are the same.

For instance:

?- sameend("teletubbies", R).
R = "telet";
R = "ele";
R = "eletubbie";
R = "etubbie";
R = "bb";
false.

My approach to this problem is that I have to iterate over the string with head / tail and find the index of the next letter that matches the current one (it satisfies the minimum requirement of 2 lengths) and cuts the substring using a predicate sub_string.

+4
source share
2 answers

, . Prolog . , , . . .

:- set_prolog_flag(double_quotes, chars).

sameend(Xs, Ys) :-
   phrase( ( ..., [C], seq(Zs), [C], ... ), Xs),
   phrase( ( [C], seq(Zs), [C] ), Ys).

... --> [] | [_], ... .

seq([]) -->
   [].
seq([E|Es]) -->
   [E],
   seq(Es).
+3

Prolog append/2 last/2 (lists), ,

sameend(S,[F|T]) :-
    append([_,[F|T],_],S),last(T,F).
0

Source: https://habr.com/ru/post/1674897/


All Articles