Prolog - Numbers greater than x

2019-07-13 19:38发布

问题:

I'm working with Prolog arithmetic and have a program that generates an abstract syntax tree, such as plus(num(1),num(2)) which simply is 1+2. This is done by using DCG. In this example plus(num(1),num(2)) is the same as the prefix list representation [+,1,2].

My problem is that I only want to allow num(x) greater than 3. For example num(4) is allowed but not num(1).

I'm doing this by:

num(num(4)) --> [4].
num(num(5)) --> [5].
num(num(6)) --> [6].
num(num(7)) --> [7].

etc. but would like to do something like num(num(x)) --> [x]. for numbers greater than 3. Any idea as to how to approach this problem?

回答1:

How about:

num(num(X)) --> [X], {X > 3}

The {}/1 can be used to embed conditions and side effects in DCG grammar rules. DCGs are found in many Prolog systems but there is not yet a ripe standard. But most of the Prolog systems do have the {}/1. It is for example defined here:

Definite Clause Grammar Rules
Klaus Daessler
August 20, 2013
http://www.complang.tuwien.ac.at/ulrich/iso-prolog/dcgs/dcgsdin130820.pdf

In the glossary the {}/1 goes as "grammar body goal". In older publications the construct was called "auxiliary action", "procedure call" or "extra conditions", which is probably more sensible than just calling it grammar body goal, since we would like to see all constituents of a grammar body as grammar body goals. See for example here:

Definite Clause Grammars for Language Analysis
Fernando C. N. Pereira and David H. D. Warren
Artificial Intelligence 13 (1980), 231-278
http://cgi.di.uoa.gr/~takis/pereira-warren.pdf

Bye