Sam
Sam

Reputation: 2341

Prolog: Checking if the first and last character of a string are left and right squiggly brackets('{' & '}')

I am very new to prolog, so assume that I know very little terminology. I am using swipl in SWI-prolog.

I want to check if a string starts with a left squiggly bracket('{') and ends with a right squiggly bracket('}'}

Some answers that I have read online have lead me to program the following into my knowledge base to check if the string starts with a left squiggly bracket.

start_left_squiggle([Letter|_]):-
     Letter = '{'.

But when I run this function, I get false, when I expect it to return true.

?- start_left_squiggle('{hello').
false.

As well, answers that seem correct for checking the if the last character is a squiggly bracket have lead me to code the following.

last_char(str, X):-
    name(S, N), 
    reverse(N, [F|_]),
    name(X, [F]).

end_right_squiggle(Werd):-
    last_char(Werd, Last),
    Last = '}'.

And I again get false when running the function, when I expect it to return true.

?- end_right_squiggle('hello}').
false.

Upvotes: 2

Views: 1465

Answers (2)

false
false

Reputation: 10122

Use sub_atom(Atom, Before, Length, After, Subatom) like so:

?- sub_atom('{abc}',0,1,_,C).
   C = '{'.
?- sub_atom('{abc}',_,1,0,C).
   C = '}'.

Or just test:

?- sub_atom('{abc}',0,1,_,'{').
   true.
?- sub_atom('{abc}',_,1,0,'}').
   true.

Upvotes: 3

Luai Ghunim
Luai Ghunim

Reputation: 976

First thing you need to do is to break the atom into list of characters like this:

start_with_left(H):-
   atom_chars(H,X), %here x is a list
   X = [L|_],  %get the head of the list which is frist element an compare
   L == '{'.

You can use a recursive definition to check righ side of the atom after converting the atom into list of characters and when length of the list is 1 then compare it with bracket , it means if last element is same you should get true otherwise False.

Right is like this, it's same but we need last element so we have to use recursion:

start_with_right(H):-
    atom_chars(H,X), %here x is a list
    length(X,Y),
    check_at_end(X,Y).

check_at_end([H|_],1):-
    H == '}'.

check_at_end([_|T],Y):-
    NewY is Y -1,
    check_at_end(T,NewY).

.

Upvotes: 1

Related Questions