3

次の Prolog コードを検討してください。入力内の特定のタイプの行を編集し、変更なしで残りの行を出力します。rule質問には重要ではないため、以下に含まれていないDCG を使用します。

go:-
    prompt(_, ''),
    processInput.

processInput:-
    read_line_to_codes(current_input, Codes),
    processInput(Codes).

processInput(Codes):-
    (Codes \= end_of_file
    ->
        (phrase(rule(Part1, Part2), Codes)
        ->
            format('~s - ~s\n', [ Part1, Part2 ])
        ;
            format('~s\n', [ Codes ])),
        processInput
    ;
        true).

:- go, halt.

これはうまくいきます。ただし、processInput/1次のように変更すると、Warning: /home/asfernan/tmp/tmp.pl:28: Goal (directive) failed: user: (go,halt).

processInput(Codes):-
    (Codes \= end_of_file
    ->
        (\+phrase(rule(Part1, Part2), Codes)
        ->
            format('~s\n', [ Codes ]))
        ;
            format('~s - ~s\n', [ Part1, Part2 ]),
        processInput
    ;
        true).

phrase(rule(Part1, Part2), Codes)DCG マッチの if & else 部分が入れ替わっています。これは明らかに初心者の間違いですが、失敗したという事実go, haltはあまり役に立ちません。Part1&Part2が行にバインドされていないためにエラーが発生したことをエラー メッセージに示すにはどうすればよいformat('~s - ~s\n', [ Part1, Part2 ])ですか? コードが小さいため、このエラーを突き止めることができましたが、コードが大きかったと追跡できなかった可能性があります。

4

1 に答える 1

4

In Prolog the following is not the same:

..., ( Cond -> Then ; Else ), ...

and

..., ( \+ Cond -> Else ; Then ), ...

In general, a goal \+ Cond will never instantiate its variables. So you have to stick to the original formulation.

In case you are interested to process entire files with DCGs, consider SWI's library(pio).

于 2011-06-02T17:49:58.627 に答える