定子句语法(DCG)的Prolog(作业)(definite clause grammar (dcg

2019-10-23 14:20发布

我试图写一个谓语和N={Expression,Number,Digit,Operator,Variable}

T={1,2,3,+,-,*,(,),X,Y,Z}和S被表达和程序P定义为

Expression-->Number
**Expression-->(Expression) Operator (Expression)**
Number-->Digit
**Number --> Digit Number**
Digit-->1
Digit-->2
Digit-->3
Operator-->+
Operator-->-
Operator-->*
Variable-->X
Variable-->Y
Variable-->Z

我想,我实现了很多地方却无法执行大胆的零件!

描述由根据程序P端子我序言代码:

 expression(S,S).
    expression(S,R):-number(S,R).
    expression(S,R):-expression(S,R),-operator(S,['('|S]),expression(S,[')'|R]).
    expression(S,R):-operator(S,[','|S1]),expression(S1,R).
    expression(S,R):-variable(S,[','|S1]),expression(S1,R).
    number(S,R):-digit(S,R).
    digit(['1'|R],R).
    digit(['2'|R],R).
    digit(['3'|R],R).
    operator(['+'|R],R).
    operator(['-'|R],R).
    operator(['*'|R],R).
    variable(['X'|R],R).
    variable(['Y'|R],R).
    variable(['Z'|R],R).

请帮我。

Answer 1:

这可能是DCG你的意思是:

:- set_prolog_flag(double_quotes, chars).

expression --> number.
expression --> variable.
expression --> "(", expression, operator, expression, ")".

number --> digit.
number --> digit, number.

digit --> "1".
digit --> "2".
digit --> "3".

operator --> "+"|"-"|"*".  % more compact notation
variable --> "X"|"Y"|"Z".

使用它像这样产生的长下令所有的句子:

?- length(L, N), phrase(expression, L).
L = ['1'],
N = 1 ;
L = ['2'],
N = 1 ;
L = ['3'],
N = 1 ;
L = ['X'],
N = 1 ;
L = ['Y'],
N = 1 ;
L = ['Z'],
N = 1 ;
L = ['1', '1'],
N = 2 ;
L = ['1', '2'],
N = 2 ...

并获得最紧凑和可读的答案看到这个更多。 也就是说,下载以下模块:

?- use_module(double_quotes).
?- length(L, N), phrase(expression, L).
L = "1",
N = 1 ;
L = "2",
N = 1 ;
L = "3",
N = 1 ;
L = "X",
N = 1 ;
L = "Y",
N = 1 ;
L = "Z",
N = 1 ;
L = "11",
N = 2 ;
L = "12",
N = 2 

要查看DCG是如何实现的,说listing的每个非终端。 例如:

?- listing(expression).
expression(A, B) :-
        number(A, B).
expression(A, B) :-
        variable(A, B).
expression(['('|A], E) :-
        expression(A, B),
        operator(B, C),
        expression(C, D),
        D=[')'|E].


文章来源: definite clause grammar (dcg) Prolog (homework)
标签: prolog dcg