Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AI and Deep Learning by (50.2k points)

I'm writing a Lisp to C translator and I have a problem with handling strings. This is a code that transforms a unary Lisp function to a C equivalent:

define(F) --> fun_unary(F), 

!. fun_unary(F) --> "(define (", label(Fun), spaces, label(Arg1), ")", spaces, expr(Body), ")", {swritef(F, "data *%t(data *%t) { return(%t); }", [Fun, Arg1, Body])}, !. funs([F]) --> define(F), !. funs([F|Fs]) --> define(F), spaces, funs(Fs), !.

Now I want to read any number of functions and return them as a single string. The above funs is the best I could come up with, but it works like this:

?- funs(F, "(define (carzero l) (= (car l) 0)) (define (zero n) (= 0 n))", []). F = ["data *carzero(data *l) { return(eq(car(l), make_atom_int(0))); }", "data *zero(data *n) { return(eq(make_atom_int(0), n)); }"].

While I want something like this:

F = "data *carzero(data *l) { return(eq(car(l), make_atom_int(0))); }\n\ndata *zero(data *n) { return(eq(make_atom_int(0), n)); }".

so that I can nicely swritef is into a complete program, between #includes and main(). An alternative solution is to modify the highest level translator to handle the list. It currently looks like this:

program(P) --> define(F), {swritef(P, "#include \"lisp2c.h\" \n\n%t \nint main() { return 0; }", [F])}, !.

How would I do any of these two? I'm using SWI Prolog.

1 Answer

0 votes
by (108k points)

Code for Prolog program to read two strings and then output the third-string which is a concatenation of both excluding repeating characters in Artificial Intelligence.

predicates

    start

    comp_str(string,string,string)

    comp_char(string,string,char,string)

goal

    clearwindow,

    start.

clauses

    start:-

        write("Enter first string = "),

        readln(Str1),nl,

        write("Enter second string = "),

        readln(Str2),nl,

        comp_str(Str1,Str2,Str3).

    comp_str(Str1,Str2,Str3):-

        Str2 <> "",

        frontchar(Str2,Char2,Rest2),

        comp_char(Str1,Str1,Char2,Str3),

        comp_str(Str3,Rest2,Str4).

    

    comp_str(Str1,Str2,Str3):-

        write("concat string = ",Str1).

        

    comp_char(Str1,TempStr1,Char2,Str3):-

        TempStr1 <> "",

        frontchar(TempStr1,Char1,Rest1),

        Char1 <> Char2,

        comp_char(Str1,Rest1,Char2,Str3).

    comp_char(Str1,TempStr1,Char2,Str3):-

        TempStr1 <> "",

        Str3 = Str1.

    comp_char(Str1,TempStr1,Char2,Str3):-

        str_char(Str2,Char2),

        concat(Str1,Str2,Str3).

 For a better understanding of the concatenation of the two lists refer to the following link:

https://www.swi-prolog.org/pldoc/doc/_SWI_/library/lists.pl

Browse Categories

...