prolog - parsing an expression using DCG -
i try parse list of identifiers dcg fail it,
example
::= | __|____ | | id id,'(',ids,')'. _|_ | | id id,
-
ids ::= id. ids ::= id(id1,id2,...).
example of identifier verify
exp1 = 'id_0' exp3 = 'id_1(i)' exp2 = 'id_2(i1,i2)'
code edit
id([id]) --> [id]. id([id|ids]) --> [id,'('], ids(ids), [')']. ids([id]) --> [id]. ids([id|ids]) --> [id], ids(ids).
someone tell me problem ?
let first see currently describing (for example) id//1
, using most general query:
?- phrase(id(is), ls). = ls, ls = [_g884] ; = [_g884|_g885], ls = [_g884, '(', ids(_g885), ')'].
trying out general query way find out more relation. in case, note 2 important things:
- regarding list
ls
of tokens, first solution more general intended. no clause add program (while preserving logical-purity) can remove flaw. therefore, need make first rule more specific. - the tokens described second answer not match grammar, because contain concrete token
ids(_)
. points fact intermingling dcg rule names tokens want describe.
for start, let first focus describing list of tokens want describe. simplifies code somewhat, since not have deal many things @ once.
i suggest start following:
ids --> [id]. ids --> [id,'('], ids_, [')']. ids_ --> ids, more_ids_. more_ids_ --> []. more_ids_ --> [,], ids_.
notice helpful pattern allows specify "more of same", either nothing or comma and then "the same".
i suppose make more general, , example accept other identifiers besides concrete token id
. place clear code above, , leave easy exercise.
notice can use see whether describing only intended lists of tokens:
?- length(ls, _), phrase(ids, ls). ls = [id] ; ls = [id, '(', id, ')'] ; ls = [id, '(', id, ',', id, ')'] ; ls = [id, '(', id, '(', id, ')', ')'] ; etc.
i using length/2
fair enumeration.
once have made sure describing , lists of tokens intended, can start relate such lists of tokens other prolog terms. involve (=..)/2
, other relations between terms.
Comments
Post a Comment