EvgSkv / logica

Logica is a logic programming language that compiles to SQL. It runs on DuckDB, Google BigQuery, PostgreSQL and SQLite.
https://logica.dev
Apache License 2.0
1.89k stars 95 forks source link

how to launch a subset query? #165

Open sunriseXu opened 3 years ago

sunriseXu commented 3 years ago

hi, do logica have subset function? I want to compare one set to another, and return a boolean value showing whether the two sets are equal or subset? eg: SUBSET({ }, { }) = TRUE SUBSET({ 1, 2, 3 }, { }) = TRUE SUBSET({ 1, 2 }, { 1, 2 }) = TRUE SUBSET({ 1, 2, 3 }, { 1, 2 }) = TRUE SUBSET({ 1, 3, 5 }, { 1, 2 }) = FALSE many thanks!

EvgSkv commented 3 years ago

Hello!

We need to check membership in the second list for each element in the first list. Here is the implementation and a test:

@Engine("sqlite");

# Returns 1 if a is subset of b and 0 otherwise.
# To call as a predicate call Constraint(Subset(a, b)). 
Subset(a, b) = result :-
  result_or_null Min= (e in b :- e in a),
  result == Coalesce(result_or_null, 1);

# Testing Subset function.
Test(a, b, Subset(a, b)) :-
  (a == [], b == [1,2]) |
  (a == [1,2], b == [1,2,3]) |
  (a == [1,2,3], b == [1,2]);

Let me know if you have further questions.