Prolog- translating English to C

后端 未结 1 1215
天命终不由人
天命终不由人 2021-01-24 11:28

We have a relatively simple assignment that I understand in theory but I think I just don\'t quite understand Prolog\'s syntax enough to get that into code. Basically, we have a

1条回答
  •  孤独总比滥情好
    2021-01-24 12:09

    If there is a reasonable small number of patterns, you could do:

    english2C([add,X,to,Y], R) :- R is X+Y.
    english2C([add,A,to,B,',',then,subtract,C], R) :- R is A+B-C.
    

    edit

    Those rules above compute the value. To translate, we can use DCG for matching, it's working 'backwards' as well.

    english2C(In, R) :- phrase(toe(R), In, []).
    
    toe(X+Y) --> [add,X,to,Y].
    toe(X*Y) --> [multiply,X,by,Y].
    toe(L-R) --> toe(L), [',',then,subtract,R].
    

    test:

    ?- english2C(X,3+6).
    X = [add, 3, to, 6].
    

    edit sorry, I forgot a cut. With that added, I get

    ?- english2C([add,3,to,5,',',then,subtract,4],X).
    X = 3+5-4.
    
    ?- english2C(L,3+5-4).
    L = [add, 3, to, 5, ',', then, subtract, 4].
    

    without, there is the loop after ;

    ?- english2C([add,3,to,5,',',then,subtract,4],X).
    X = 3+5-4 ;
    ^CAction (h for help) ? goals
    [698,875] toe(_G2096630, [add, 3, to, 5, ',', then, subtract, 4], _G2096652)
    [698,874] toe('', '', _G2096652)
    ...
    

    It's a single point change: do you prefer to find it yourself?

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