0

Is it possible to use Prolog DCG in order to parse an "if-then-else" statement? If so, how does one parse such a statement, given that I must match the particular "if" "then" "else" strings. If this isn't possible, what are my alternatives?

false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

0

DCG are perfectly suited. But being barebone Prolog, you must do some choice to harness the power and implement anything practical. For instance, when possible I apply DCGs directly on textual source, without a preliminar tokenizer. If this is appropriate, depends on the actual task. Let's assume it's ok here. Then our DCG could be implemented in SWI-Prolog, using the available helper library:

:- [library(http/dcg_basics)].

conditional(if_then_else(Cond, Then, Else)) -->
  blanks, "if",
  blanks, bool_expression(Cond),
  blanks, "then",
  blanks, statement(Then),
  blanks, "else",
  blanks, statement(Else).

Very easy, isn't it?

This other answer shows how to parse (and evaluate) expressions, accounting for precedence. You can easily extend it with the boolean operators, just give them the right precedence. Statement tipically will allow assignements and will recurse on conditional.

You must pay attention to usage of blanks//0, being a possibly 'empty match' production could introduce some inefficiency if appears 'side by side' to some other production with the same property.

When bool_expression//1 and statement//1 have been defined, the parser can be invoked:

...,
phrase(conditional(C), "  if 1 < 2 then a = 1 else a = 0  "),
...

and C will contain the syntax tree...

Community
  • 1
  • 1
CapelliC
  • 59,646
  • 5
  • 47
  • 90