Very basic dcg prolog syntax

后端 未结 2 1290
广开言路
广开言路 2021-01-19 11:21

I am trying to understand prolog and definite clause grammar but I am having a very hard time understanding both of them.

I am really trying to understand how to use

相关标签:
2条回答
  • 2021-01-19 12:08

    DCG: foo(A1, A2, A3, ... , An) --> bar.

    Prolog: foo(A1, A2, A3, ... , An, X, Y) :- bar(X,Y)

    So, s should be changed to:

    s(X) --> first(X), operator, second.
    first(X) --> [X].
    operator --> ['+'].
    second --> [X].
    

    Of course, it might be better to return the actual result; to do this you should encapsulate prolog code in the DCG clause which is done with {}:

    s(Z) --> first(X), operator, second(Y), {Z is X+Y}.
    first(X) --> [X].
    operator --> ['+'].
    second(X) --> [X].
    

    (naturally, if you have more operators, the prolog code won't be that simple).

    Regarding the do/4 predicate, it should be something like this:

    do(X,Y,[H|T],Sum) -->
       {H == 1, %check if H is 1
        X = H,
        Y = T,
        Additional is H+5,
        Sum is Additional+Additional}.
    

    but I don't see why you would want that.

    One last tip: it's recommended to use phrase/3 instead of adding the last two arguments in a DCG predicate.

    0 讨论(0)
  • 2021-01-19 12:14

    it's not easy to translate do/4 to DCG in meaningful way. I've removed arguments that 'copy' the hidden arguments of the DCG.

    do(Sum) -->
        [1],  %check if H is 1
        {  % braces allow 'normal' Prolog code (but we have no access to 'hidden' arguments)
        Additional is H+5,
        Sum is Additional+Additional
        }.
    

    edit sorry I forgot H in Additional is H+5,, should read Additional is 1+5,...

    0 讨论(0)
提交回复
热议问题