Prolog - Numbers greater than x
Asked Answered
S

1

1

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?

Scribe answered 13/11, 2013 at 16:53 Comment(4)
@ChristianF Yes, it's an exercise! I'm willing to learn, so just the slightest hint will be appreciated! :) I've been researching, but it's not a lot of Prolog-stuff out there...Scribe
You don't seem to understand the concept of variables in Prolog. Read up about that. After that, read up about DCGs. You shouldn't use it in this case. Then, realize that it is trivial to check X > 3.Bergamot
Thanks again! Figured it out ;)Scribe
@ExceptionalException: Then write your own answer.Requisite
D
3

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

Durante answered 14/2, 2014 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.