明确的条款语法(dcg)Prolog(家庭作业)

时间:2015-07-01 21:02:11

标签: prolog dcg

我试着写一个谓词和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

我认为我实现了很多部分,但无法实现大胆的部分!!

我的prolog代码,通过依赖程序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).

请帮帮我。

1 个答案:

答案 0 :(得分:4)

这可能是你想要的

:- 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 ...

要获得最简洁易读的答案,请参阅this了解更多信息。也就是说,下载以下模块:

?- 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。 E.g:

?- 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].