h.zuhair
h.zuhair

Reputation: 9

how to compare last element of a list with last element of another list in prolog?

I want to find rhyming couplets of a poem so I need to compare last syllables of two verses of the poem.

cmp([A|As], [B|Bs]) :- cmp(As, A, Bs, B).

cmp(A, [B], B, [A]).
cmp([_, A|As], X, [_, B|Bs], Y) :- cmp([A|As], X, [B|Bs], Y).

I need, for example, to check if "[They, put, me, in, the, oven, to, bake]" and "[Me, a, deprived, and, miserable, cake]" rhymes, so I suppose I should check if last elements of these two lists are the same.

With this code i tried to compare first and last elements of my lists but it doesn't work neither.

Upvotes: 0

Views: 40

Answers (2)

Paulo Moura
Paulo Moura

Reputation: 18663

Some Prolog systems provide a lists library with a last/2 predicate that you can call. The usual definition is:

last([Head| Tail], Last) :-
    last(Tail, Head, Last).

last([], Last, Last).
last([Head| Tail], _, Last) :-
    last(Tail, Head, Last).

Note that this definition avoid a spurious choice-point, thanks to first-argument indexing, when calling the predicate with a bound list.

Using the last/2 predicate you can write:

compare_verses(Versus1, Versus2) :-
    last(Versus1, Word1),
    last(Versus2, Word2),
    same_last_syllable(Word1, Word2).

You will now need to define the same_last_syllable /2 predicate. That will require breaking a word into a list of syllables. That doesn't seem to be trivial (see e.g. https://www.logicofenglish.com/blog/65-syllables/285-how-to-divide-a-word-into-syllables) and I'm not aware of a open source Prolog library performing it.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

It sounds like you need, at least in part, a way to identify the last element of a list:

last_of( [X], X ).
last_of( [_|X], Y ) :- last_of(X, Y).

Upvotes: 0

Related Questions