SQL simulator on Prolog

259 Views Asked by At

i need to do a SQL simulator on Prolog. i need to simulate some functions like create_table, insert, delete, update_table, select_table, drop_table, show_table, etc. I am learning how to do asserts and retracts but im getting some errors in my first function create_table(N,A) where N is the name of the table and A a list with the atributtes

An example is create_table("student",["name","lastname","age"]). This will create my table named "student" with the atributes ["name","lastname","age"].

I was searching how to work with assert and i see i need to do dynamic before making assert, then my code is.

len([],0). 
len([_|T],N)  :-  len(T,X),  N  is  X+1.

create_table(_, []):-!.
create_table(N, Atributos):- len(Atributos, L), dynamic N/L, assert(N(Atributos)).

But i get this error :7: Syntax error: Operator expected on this line

create_table(N, Atributos):- len(Atributos, L), dynamic N/L, assert(N(Atributos)).

What im doing wrong? excuse me, i dont speak good english.

2

There are 2 best solutions below

2
On

From the error message, seems you're using SWI-Prolog.... Your code could be (note that len/2 can be replaced by the builtin length/2)

create_table(N, Atributos):-
 length(Atributos, L),
 dynamic(N/L),
 T =.. [N|Atributos], % this missing 'constructor' was the cause of the error message
 assert(T). % this is problematic

There is an important 'design' problem: the CREATE TABLE SQL statement works at metadata level.

If you do, for instance,

?- assertz(student('Juan', 'Figueira', 20)).

pretending that the predicate student/3 holds table data, you're overlapping data and metadata

3
On

using dynamic/1 and assert is a tricky non-logical aspect of Prolog, and dynamically creating dynamic predicates is really unusual. Fundamentally you cannot have a Prolog query with the predicate name as a variable e.g.

query(N,X) :- N=student, N(X).

My suggestion is you remove a layer of complexity and have one dynamic predicate 'table', and assert your SQL tables as new 'table' clauses i.e.

:- dynamic table/2.

:- assertz(table(student,['Joe','Young',18])).

query(N,X) :- table(N,X).

:- query(student,[Name,Lastname,Age]).