Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog Backtracking

I am trying to do a word calculator .. read words from a file .. translate them into numbers and then calculate the result .. i managed to do all of that but i think i have two bugs in my program ..

I mainly have two functions ...

extract(Words), calculate( Words,0).

extract will read from the file .. and then return a list of Words .. ex: [one,plus,three] .. now calculate will translate the value for these words into numbers and calculate .. i managed to do that also .. now the bugs are : i must stop reading and terminate if i encounter stop in the file .. so if Words was [stop] End. i tried the following ...

execute :-
 extract(Words),
 Words = [stop],nl,print('Terminating ...'),!.
execute :-
 extract(Words),
 calculate( Words,0).

it successfully terminates .. but it skips lines as i extract more than once .. i have tried to do ..

execute :-
 extract(Words),
 Words \= [stop],execute(Words).
execute(Words) :-
 calculate( Words,0).

if the Words is not stop .. then go and calculate .. but its not working !!

i appreciate the help .. Thank You

like image 732
AhmadAssaf Avatar asked Dec 18 '25 04:12

AhmadAssaf


1 Answers

Side-effects (here: reading from a file and moving on to the next term) are not undone on backtracking. You can read once and then make the choice based on the read term with if/then/else or an auxiliary predicate, for example:

execute :-
        extract(Words),
        (   Words == [stop] -> nl, write('Terminating ...')
        ;   calculate(Words, 0)
        ).

In SWI-Prolog, consider using library(pio) for pure file reading described via dcg, which handles backtracking as expected.

like image 107
mat Avatar answered Dec 20 '25 04:12

mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!