Question

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

Was it helpful?

Solution

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 , which handles backtracking as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top