RegEx Parser written in Prolog

前端 未结 2 1526
自闭症患者
自闭症患者 2021-01-02 15:19

I\'ve been banging my head against the wall on this homework problem for a few hours now. We have to parse a regular expression with Prolog. For the most part, the predicat

相关标签:
2条回答
  • 2021-01-02 15:38

    I don't have access to SWI Prolog right now, but here is a guess:

    Try changing

    re_match(star(Rx), List) :- append(List1, List2, List),
                                re_match(Rx, List1),
                                re_match(star(Rx), List2).
    

    to

    re_match(star(Rx), List) :- append([H|List1], List2, List),
                                re_match(Rx, [H|List1]),
                                re_match(star(Rx), List2).
    

    to force re_match to "eat something" when it iterates on the star construct.

    0 讨论(0)
  • 2021-01-02 15:50

    Consider using DCG notation for better readability and to more easily reason about termination properties:

    :- op(100, xf, *).
    
    rexp(eps)      --> [].
    rexp([T])      --> [T].
    rexp(_*)       --> [].
    rexp(R*)       --> rexp(R), rexp(R*).
    rexp(s(R1,R2)) --> rexp(R1), rexp(R2).
    rexp((R1|R2))    --> ( rexp(R1) ; rexp(R2) ).
    

    Example using length/2 to generate increasingly longer lists to generate strings that are matched by the regexp:

    ?- length(Ls, _), phrase(rexp(s(([a]|[b]),[c]*)), Ls).
    Ls = [a] ;
    Ls = [b] ;
    Ls = [a, c] ;
    Ls = [b, c] ;
    Ls = [a, c, c] ;
    etc.
    
    0 讨论(0)
提交回复
热议问题