LoginSignup
1
2

作業用スクリプトをPrologで書く

Posted at

作業用スクリプトをPrologで書く

スクリプトファイル単体でいい感じに実行できたので導入手順とテンプレートを載せておきます。

インストール

Prologの処理系はいくつかあるが、恐らく一番メジャーなSWI-Prologを利用します。

brew install swi-prolog

スクリプトファイル作成

拡張子は .swi.plのいずれかであるが、.plだとPerlの拡張子と被るので .swiの方が良いです。
sample.swiというスクリプトファイルを作成して、以下の内容を記述します。

#!/bin/sh swipl

% プログラム実行時の引数を取得する
get_command_line_arguments(Arguments) :-
    current_prolog_flag(argv, Arguments).

% 外部コマンドを実行する
run_command(Command, ExitCode) :-
  shell(Command, ExitCode).

% 外部コマンドを実行する(実行結果も取得)
run_command_with_output(Command, Output) :-
    process_create(
        path(sh),
        [ '-c', Command ],
        [ stdout(pipe(Out)), stderr(pipe(Err)) ]
    ),
    (
        read_string(Out, _, Output),
        close(Out),
        read_string(Err, _, ErrorOutput),
        close(Err),
        (ErrorOutput == '' -> true ; writeln(ErrorOutput))
    ).

% 実際の使用例
main :-
    % 外部コマンドを実行
    writeln('コマンドの実行結果'),
    run_command('ls', ExitCode),
    write('コマンドのExitCode : '),
    writeln(ExitCode),

    writeln('コマンドの実行結果(結果も取得)'),
    run_command_with_output('ls', Output),
    writeln(Output),

    write('プログラム引数 : '),
    % 引数を取得
    get_command_line_arguments(Arguments),
    writeln(Arguments).

% メインを実行
:- initialization(main, main).

この状態で以下のコマンドを実行してファイルに実行権限を与えます。

chmod +x sample.swi

あとは以下のように実行すればOKです。

sample.swi

プログラムのベースはChatGPTを利用して作成しましたが、そのままだと動かなかったので一部修正してあります。
ChatGPTが取り込んだサンプルにPrologが少なかったのかは不明ですが、「実際のSWI-Prologのバージョンで使われるのはcreate_process/4です」などと嘘を言ってくるので、完全に信頼はできないですね。。。

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2