RegEx Parser written in Prolog

前端 未结 2 1530
自闭症患者
自闭症患者 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: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.
    

提交回复
热议问题