简体   繁体   中英

Why is this rule not consuming the first character [Prolog CFG]?

I am trying to write a rule for wrapping elements but when entering the recursive rule, the first element is still being included, maybe I am not understanding correctly the syntax but the comma shouldn't go to the next element?

% [First] should be consumed (note: charcode 194 is for the backtick character)
backticks(L) --> [First], {char_code(First,194), writeln(["first was backtick",First])}, nobackticks(L), {writeln(["identifier",L])}.
nobackticks([]) --> [Last], {char_code(Last,194),writeln(["last is backtick",Last])}.
nobackticks([X|Xs]) --> [X], nobackticks(Xs), {writeln(["checking backticks",X,Xs])}.
%run recursively until it finds the last backtick

Test

:- string_chars("´backticks´",Text), phrase(backticks(X),Text,[]), writeln(X).

Output:

[first was backtick,´]
[last is backtick,´]
[checking backticks,s,[]]
[checking backticks,k,[s]]
[checking backticks,c,[k,s]]
[checking backticks,i,[c,k,s]]
[checking backticks,t,[i,c,k,s]]
[checking backticks,k,[t,i,c,k,s]]
[checking backticks,c,[k,t,i,c,k,s]]
[checking backticks,a,[c,k,t,i,c,k,s]]
[checking backticks,b,[a,c,k,t,i,c,k,s]]
[checking backticks,´,[b,a,c,k,t,i,c,k,s]]
[identifier,[´,b,a,c,k,t,i,c,k,s]]

Expected output:

[identifier,[b,a,c,k,t,i,c,k,s]]

Finally the rule is not successful

If you run ?- char_code(´,C). you get C=180 (at least in SWISH). So you need to change 194 to 180 in your code and you will get the desired output:

[first was backtick, ´]
[last is backtick, ´]
[checking backticks, s, []]
[checking backticks, k, [s]]
[checking backticks, c, [k, s]]
[checking backticks, i, [c, k, s]]
[checking backticks, t, [i, c, k, s]]
[checking backticks, k, [t, i, c, k, s]]
[checking backticks, c, [k, t, i, c, k, s]]
[checking backticks, a, [c, k, t, i, c, k, s]]
[checking backticks, b, [a, c, k, t, i, c, k, s]]
[identifier, [b, a, c, k, t, i, c, k, s]]
[b, a, c, k, t, i, c, k, s]
true
false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM