Are DCG's just "syntactic sugar"?

Here is my first translation to SWI-Prolog. It works but is not done in the same manner as done with Amzi. In Amzi they parse the input into tokens then process the tokens using DCG. In my version I let the DCG do the parsing and processing. If I get a chance latter I will do the Amzi to SWI the way Amzi intended.

Here is my code


:- set_prolog_flag(double_quotes, codes).
:- set_prolog_flag(back_quotes, string).

:- dynamic
    booked/2.

main :-
    write('Fly Amzi! Air'), nl,
    repeat,
    do_command.

do_command :-
    write('enter command> '),
    read_string(user_input, "\n", "\r", _End, Input),
    string_codes(Input,Codes),
    DCG = command(Command_list),
    phrase(DCG,Codes,_Rest),
    Command =.. Command_list,
    call(Command),
    !,
    Command == exit.

command([Op|Args]) -->
    operation(Op),
    " ",
    arguments(Args).
command([Op]) -->
    operation(Op).

arguments([Arg|Args]) -->
    argument(Arg),
    optional_arguments(Args).

optional_arguments([Arg|Args]) -->
    " ",
    argument(Arg),
    optional_arguments(Args).
optional_arguments([]) --> [].

operation(report) --> "list".
operation(book) --> "book".
operation(exit) --> ("exit"; "quit"; "bye").

argument(passengers) --> "passengers".
argument(flights) --> "flights".

argument(Flight) -->
    argument_item(Flight),
    {
        flight(Flight)
    }.
argument(Passenger) -->
    argument_item(Passenger).

argument_item(Argument) -->
    argument_codes(Codes),
    { atom_codes(Argument,Codes) }.

argument_codes([C|Cs]) -->
    argument_code(C),
    argument_codes(Cs).
argument_codes([]) --> [].

argument_code(C) -->
    \+ " ",
    \+ "\r",
    \+ "\n",
    [C].

flight(aa101).
flight(aa102).
flight(aa103).

report(flights) :-
    flight(Flight),
    write(Flight), nl,
    fail.
report(_).

report(passengers, Flight) :-
    booked(Passenger, Flight),
    write(Passenger), nl,
    fail.
report(_, _).

book(Passenger, Flight) :-
    assert(booked(Passenger, Flight)).

exit.

Example run.

?- main.
Fly Amzi! Air
enter command> list flights
aa101
aa102
aa103
enter command> book leona aa102
enter command> book ivan aa102
enter command> list passengers aa102
leona
ivan
enter command> quit
true .
2 Likes