Command Line Arguments in Prolog

Our program demonstrates how to handle command-line arguments in Prolog. Here’s the full source code:

:- initialization(main).

main :-
    current_prolog_flag(argv, Args),
    write('All arguments: '), writeln(Args),
    
    % Get arguments without the program name
    append([_|ArgsWithoutProg], [], Args),
    write('Arguments without program: '), writeln(ArgsWithoutProg),
    
    % Get a specific argument (4th in this case)
    (nth0(3, Args, FourthArg) ->
        write('4th argument: '), writeln(FourthArg)
    ;   
        writeln('4th argument not available')
    ).

In Prolog, we use the current_prolog_flag(argv, Args) predicate to access command-line arguments. The first argument in this list is typically the path to the program, and the rest are the arguments passed to the program.

To get the arguments without the program name, we use the append/3 predicate to split the list.

You can get individual arguments using list operations. In this example, we use nth0/3 to get the 4th argument (index 3).

To run the program, save it as command_line_arguments.pl and use the following command:

$ swipl command_line_arguments.pl a b c d
All arguments: [command_line_arguments.pl,a,b,c,d]
Arguments without program: [a,b,c,d]
4th argument: d

If you want to create a standalone executable, you can use the following commands:

$ swipl -o command_line_arguments -c command_line_arguments.pl
$ ./command_line_arguments a b c d
All arguments: [./command_line_arguments,a,b,c,d]
Arguments without program: [a,b,c,d]
4th argument: d

This creates a standalone executable that you can run directly.

Next, we’ll look at more advanced command-line processing techniques in Prolog.