DCG : zero-or-more, zero-or-one , one-or-more occurrences?

Viewed 100

In DCG how do you implement : zero-or-more, zero-or-one , one-or-more occurrences ?

I'm talking about the following in pseudo code :

  sentence --> word+
  float --> int+, ['.'], int+
  nilORa --> a? 
  nilORaaaa --> a*
1 Answers

You use the or-nondeterminism offered by the clause set of a predicate (or, in this case, the set of DCG productions for the same DCG "nonterminal" - the DCG production is an alternative notation for a Horn clause)

Move the production that should be performed first to the top. For example, to collects at least one word, but possibly more, greedily:

sentence --> word, sentence.
sentence --> word.

Depending on how much determinism is in the grammar, you can even cut:

sentence --> word, !, sentence.
sentence --> word.

Same with a float. digits is at least one digit. There already is a definition for digit in the library I think:

float --> digits, ['.'], digits.

digits --> digit, digits.
digits --> digit.

nilORa is an a -- or possibly nothing:

nilORa --> a.
nilORa --> [].

nilORaaaa is an a followed by nilORaaaa -- or possibly nothing:

nilORaaaa --> a, nilORaaaa.
nilORaaaa --> [].

You should also be able to deploy ; I think:

nilORaaaa --> (a, nilORaaa) ; [].
Related