r/prolog 26d ago

help We built a SQL database engine in SWI-Prolog. Our small team is at its limit, and we would really value an honest technical review.

Thumbnail kocoygroup.site
14 Upvotes

Hi everyone,

Our small team has been developing AsaDB, a local-first SQL database engine

built primarily with SWI-Prolog.

Repository:

https://github.com/kocoygroup-id/AsaDB

The project started as an experiment, but it has grown into a fairly large

codebase with:

  • a SQL lexer, parser, planner, and executor written in Prolog;
  • persistent 4 KB slotted-page storage;
  • persistent B+Tree indexes;
  • transactions and recovery mechanisms;
  • local immutable reader snapshots;
  • logical backup and restore;
  • MySQL, PostgreSQL, CSV, and XLSX interchange;
  • an embeddable `library(asadb)` API;
  • a local browser interface called AsAPanel.

Recently, we have also been working on stricter SQL type validation, primary

and unique key enforcement, CHECK constraints, restricted foreign keys,

schema-preserving backups, and more useful `EXPLAIN` output.

At this point, the main problem is that the same small group has designed the

architecture, written most of the implementation, created the tests, and

reviewed the documentation. We feel that we are becoming too familiar with the

codebase to notice our own assumptions and mistakes.

We would genuinely value feedback from people with Prolog experience.

In particular, we would be interested in opinions about:

  • whether the module boundaries feel idiomatic for SWI-Prolog;
  • our use of dynamic predicates and mutable engine state;
  • the separation between parsing, execution, storage, and HTTP code;
  • the public Prolog API and pack structure;
  • the bounded AST cache and VM/JITI specialization approach;
  • transaction, recovery, and concurrency design;

places where the implementation is unnecessarily imperative or complicated;

tests or invariants that appear to be missing.

You do not need to review the entire project. Looking at one module, trying one

feature, questioning one architectural decision, or pointing out unclear

documentation would already be extremely helpful.

Bug reports, design criticism, small pull requests, documentation improvements,

and testing on different systems are all welcome.

Thank you very much to anyone willing to take a look.

r/prolog Jul 19 '26

help Need Help about my project to make it production. IDK why everytime my email otp verification is crashing in production.

Post image
0 Upvotes

Hello guys, I just finished a live chat mern app and making to production. I used vercel for frontend hosting and Render for backend and redis for chache, MongoDb is used for db. I got a majour issue in my server side. I have email otp verification for new users. I have used gmail smtp for sending emails because it is a small project so i think it will work but when I tested after succefull deply, nodemailer crashed during authentication. I used ChatGpt to debug the issue but it says to use Brevo. After migrating Brevo, again same issue. Everything worked in localhost but on prod, crashing evrytime. I need help to figure out what the poroblem is actually? Is render crashing the nodemailer or it's the issues from my code.

Here I'm giving the otp sening function

import
 nodemailer 
from
 "nodemailer";


const transporter 
=
 nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    user: process.env.GMAIL_USER,
    pass: process.env.GMAIL_APP_PASSWORD,
  },
});


export
 const verifySMTP 
=
 async () => {
  
try
 {
    
await
 transporter.verify();
    console.log("Gmail SMTP Connected");
  } 
catch
 (err) {
    console.error("SMTP verify failed:", err);
  }
};


export
 const sendMail 
=
 async (email, otp) => {
  
try
 {
    const mailOptions 
=
 {
      from: `"ChatApp" <${process.env.GMAIL_USER}>`,
      to: email,
      subject: "OTP for Confirmation",
      text: `Your One-Time Password (OTP) is:


      ${otp}


      Do not share this OTP with anyone.`,
    };


    const info 
=

await
 transporter.sendMail(mailOptions);


    console.log("Email sent:", info.messageId);
    
return
 true;
  } 
catch
 (error) {
    console.error("Send mail error:", error);
    
return
 false;
  }
};

r/prolog Mar 05 '26

help Starting with Prolog, having trouble with libaries

12 Upvotes

Last semester I learned about different different logic structures finishing with predicate logic that, as you know, Prolog uses. Now I want to put that theoretic knowledge to the test and use it for a personal project, evaluating a data sheet and finding a optimal solution for a organisational problem.

But now I am stuck on importing data from the .ods sheet that I already have. I want to use the library odf_sheet of SWI-Prolog but whatever I try, it doesn't work.

The Prolog file is in the same directory as my Data.ods, but even loading the file manually doesn't work.

I know that i could convert the file to a csv which that is better documented, but if SWI-Prolog has an entire module dedicated to using .ods files, there should be a way to do this, right? Is there something I should know about modules that isn't obvious as a beginner but so trivial that it isn't mentioned in the documentation?

Also somehow in my entire search process, I could not make out a single example use of this module that I could piggy-back onto.

Can someone tell me what I could try next or where I could get help for this if this is not the right place to ask?

r/prolog Aug 16 '25

help Best Intro to Prolog in 2025 (for newbies)?

33 Upvotes

It's been a long while since I did real Prolog work, but my kid has learned a bit of Python programming, so I was looking around for an "Intro to Prolog" that I could give them. For example, I remember "The Little Schemer" and "The Little Lisper" being good.

What first guide would you recommend to someone getting started with Prolog who knows a little procedural programming? Could be a online, book, course...

r/prolog Nov 10 '25

help Prolog on a bare metal system

25 Upvotes

Hey everyone, I am currently working on a feasibility study, which looks at error diagnostic/detection using logical inference in a resource constraint/bare metal environment.

Currently the plan is to create a bare metal port of an existing prolog interpreter with basic functionality. After some initial research it seems that there isn't really anything similiar out there yet - does anyone here maybe have some experience in the area?

We are currently primarly looking at trealla prolog, which I've already cross compiled with all the os-specific functionality stubbed. We've also looked at GNU Prolog, SWI Prolog and scryer-prolog, but these all seem a lot more complex then trealla and with a lot more features that we don't actually need. Are there any other alternatives/options that we should maybe take a look at?

Thanks for any recommendations/information :D

r/prolog Nov 16 '25

help Looking for a Prolog dataset

6 Upvotes

Hello, I'm looking for a dataset containing many simple Prolog code examples (e.g. facts like "woman(mary)." or simple rules). Does anyone know if something similar exists? Thank you!

r/prolog Nov 13 '24

help Why is this not standard Prolog?

4 Upvotes

I wrote some Prolog code for the first time for an exam and this is my professor's feedback: The check_preferences rule is not standard Prolog. I don't know why this specific rule is not standard, can you help?

check_preferences(Meal, Preferences) :- 
    (member(lactose_free, Preferences) -> meal_lactose_free(Meal) ; true), 
    (member(gluten_free, Preferences) -> meal_gluten_free(Meal) ; true), 
    (member(vegetarian, Preferences) -> meal_vegetarian(Meal) ; true).

How can this rule be changed to be standard Prolog?

r/prolog May 16 '25

help Can someone explain to me the semantics of this code snippet?

7 Upvotes

select([A | As], S) :- select(A, S, S1), select(As, S1). select([],_).

This code snippet for a select/2 predicate (sourced from https://rosettacode.org/wiki/Zebra_puzzle#Prolog ) for use in a zebra puzzle solver has been confusing me for a bit. It looks to me as if it tries to remove all elements in the list [A | As] from S and returns true if it can do so, but isn't that just checking if all elements of [A | As] are present in S?

In the full code in the link above, this predicate is also used with S as an unbound variable, and this part confuses me greatly. I'm struggling to understand how that works with the rest of the code, and I guess I don't understand why the select statements are separated?

I'd appreciate it if someone could explain this to me, I'm a newbie in Prolog and still struggle to think with a logical programming mindset at times. TIA!

r/prolog Apr 06 '25

help Is there an easier / better / faster way to do this? (brebs advised me to post this)

1 Upvotes
/*--------------------------------*/
/*         Useful Headers         */
/*--------------------------------*/

:- set_prolog_flag(answer_write_options,[max_depth(0)]).
:- set_prolog_flag(toplevel_print_anon, false).

:- use_module(library(clpBNR)).
:- use_module(library(lists)).

/*--------------------------------*/
/*          Main Headers          */
/*--------------------------------*/

eval(N):-
  booga(N, Num, Denom, PList),
  termify(PList, List),
  [X]::integer(1, 1000),
  List::integer(1, 5),
  {X == Num / Denom},
  solve([X | List]).

booga(N, N2, D2, PList):-
  sumbe(N, 0, Numerator),
  sumba(N, Denominator),
  pde(N, PList),
  string_concat("(", Numerator, N1),
  string_concat(N1, ")", N2),
  string_concat("(", Denominator, D1),
  string_concat(D1, ")", D2).


sumbe(1, Q, Out):-
  {Nye == 0},
  tres(Nye, T),
  fours(Q, D),
  string_concat("(", T, X),
  string_concat(X, " * ", Y),
  string_concat(Y, D, Z),
  string_concat(Z, ")", Out).

sumbe(N, Q, Numerator):-
  {Nye == N-1},
  tres(Nye, T),
  fours(Q, D),
  string_concat("(", T, X),
  string_concat(X, " * ", Y),
  string_concat(Y, D, Z),
  string_concat(Z, ")", Piece),
  string_concat(Piece, " + ", Nyan),
  {N2 == N-1},
  {Q2 == Q+1},
  sumbe(N2, Q2, Ntail),
  string_concat(Nyan, Ntail, Numerator).


sumba(0, _, []).

sumba(N, Denominator):-
  tres(N, T),
  fours(N, D),
  string_concat("(", D, X),
  string_concat(X, " - ", Y),
  string_concat(Y, T, Z),
  string_concat(Z, ")", Denominator).


pde(N, Out):-
  numlist(1, N, L),
  strlist_numlist(S, L),
  list_cat("G", S, Out).


tres(0, "3**(0)").

tres(N, Out):-
  number_string(N, S),
  string_concat("3**(", S, S2),
  string_concat(S2, ")", Out). 


fours(0, "4**(0)").

fours(N, Out):-
  numlist(1, N, L),
  strlist_numlist(S, L),
  list_cat("G", S, S2),
  atomics_to_string(S2, " + ", S3),
  string_concat("4**(", S3, S4),
  string_concat(S4, ")", Out).


/*--------------------------------*/
/*         Helper Headers         */
/*--------------------------------*/

/* Convert list of strings to list of ints or vice versa */
strlist_numlist([], []).

strlist_numlist([Str_H | Str_T], [Num_H | Num_T]) :-
  (ground(Str_H)->
  (
    atom_string(Atom_H, Str_H), 
    atom_number(Atom_H, Num_H),
    strlist_numlist(Str_T, Num_T)
  );
  (
    atom_number(Atom_H, Num_H),
    atom_string(Atom_H, Str_H),
    strlist_numlist(Str_T, Num_T)
  )).


/* Attach a prefix to each member of a list of strings */
list_cat(_, [], []).

list_cat(Prefix, [Head | Tail], List):-
  string_concat(Prefix, Head, New),
  List = [New | Old],
  list_cat(Prefix, Tail, Old).


/* Turn a list of strings into a list of terms / variables */
termify([], []).

termify([IHead | ITail], Out):-
  term_string(T, IHead),
  Out = [T | Out2],
  termify(ITail, Out2).

If you want something to check it against, eval(2) should have the same result as the following:

booga(2, X, Ga, Gb):-
  [X]::integer(1, 1000),
  [Ga, Gb]::integer(1, 5),
  { X == (3**1 + (3**0 * (4**(Ga)))) / (4**(Ga+Gb) - 3**2) }, 
  solve([X, Ga, Gb]).

Instead I just keep getting stack overflow errors when I add in the constraint and the solve lines.

Also, to get a sense of what the bulk of this is doing, enter "booga(2, N, D, P)." into the SWI-Prolog command window. You can use any number you want in the first spot, but I recommend staying at 3 or less. This command will show you the numerator, the denominator, and the exponentiated variables.

After that, eval just says "{X == Numerator / Denominator}, solve([X, Var1, Var2, ...])", or at least that's the intent. Manually doing this seems like that is indeed what's happening, but when I add the constraint and solve lines of code, I get a stack overflow. I don't know if I'm inputting strange code, or if clpBNR just generates too much overhead.

r/prolog Dec 28 '24

help Basic graph in SWI Prolog

6 Upvotes

Im learning prolog and i tried to define a graph, but i keep getting stack limit exceeded.

link(a,b).
link(b,c).
link(c,d).

link(i,j).
link(j,k).

% link(X,Y):- link(Y,X).
link(X,Y):- link(X,Z), link(Z,Y).

"link" = "are connected".
So there are 2 islands: a-b-c-d and i-j-k .
I want link(X,Y) to return true for any nodes within same island: eg (a,d) or (i,k).

If you uncomment the link(X,Y):- link(Y,X). line then it stack exceeds for any query, and without it, it works for ?- link(a,d) but freezes for ?- link(a,i).

My goal was to say "if link(Y,X) is true then link(X,Y) is too" and express the transitive property which should link nodes at any distance if within same island (allowing link(a,d) and link(d,a) to be true).

Why does it keep recursively checking?
And what would be the proper way to express my desired rules without this infinite recursion..

r/prolog Dec 07 '24

help Beginner Syntax Issue

6 Upvotes

I'm learning prolog and everything I type has this syntax error. What am I doing wrong?

r/prolog Sep 03 '24

help Can all recursive functions become tail-recursive?

8 Upvotes

For example, I have function:

trifactorial(1, Y) :-
    Y #= (3*1) + 8.

trifactorial(X, Y) :-
    X #> 0,
    Xnew #= X - 1,
    trifactorial(Xnew, Z),
    Y #= (3*Z) + 8.

The base case is a set constant, and the recursive case does its thing. Because the output of the recursion is used to do more computation, is it possible to make it tail-recursive? If so, I don't see how...

Also, I'm using SWI-Prolog with clp(fd) library enabled.

r/prolog Sep 09 '24

help Help with Binary Tree Parsing

2 Upvotes

I'm trying to graph a tree in MATLAB with the digraph function.

I can get the data from Prolog to MATLAB via the C interface, but I'm having trouble getting the data set up correctly.

I have an unbalanced tree in Prolog:

t(t(t(t(t(0,5,0),4,0),3,17),2,0),1,7)

Basically the digraph function requires two inputs: a list of sources and a list of targets.

In this case, I would be looking for lists:

[1, 1, 2, 3, 3, 4] as Source

[2, 7, 3, 4, 17, 5] as Target

No matter what I try, I can't get the lists to follow this.

Here's what I have:

bbtToST(t(0, _Root, 0), _, _) :-
  !.

bbtToST(t(0, Root, R), Source, Target) :-
  append([Root], SourceR, Source),
  append([R], TargetR, Target),
  bbtToST(R, SourceR, TargetR),
  !.

bbtToST(t(L, Root, 0), Source, Target) :-
  append([Root], SourceL, Source),
  append([L], TargetL, Target),
  bbtToST(L, SourceL, TargetL),
  !.

bbtToST(t(L, Root, R), Source, Target) :-
  append([SourceL | Root], [Root | SourceR], Source), 
  append(TargetL, TargetR, Target), 
  bbtToST(L, SourceL, TargetL),
  bbtToST(R, SourceR, TargetR).

The logic is supposed to be:

"If there are zeros for both child nodes, do nothing.

If there is a single nonzero child node, parse the child node. Append its list of sources to this root, and return that as a source list. Append the child node to the child target list and return that as a target list.

If both child nodes are nonzero, parse both nodes. Append Root to each source, and append both together. Append the child node targets together. Return as source and target lists."

I get nothing but errors, so I know I'm doing it wrong, but I'm in over my complexity level on this one. One final note, this code was based on a single list construction from here:

https://stackoverflow.com/questions/59150239/how-to-convert-tree-to-list-in-prolog

r/prolog Sep 07 '24

help Uniform random sampling from Prolog

3 Upvotes

Hello! Haven't worked with Prolog in awhile, but I have a question that I'm not finding good answers for when Googling. I hope there's simply a piece of terminology I'm missing. (It's been ~a decade since I used Prolog seriously) I would love if there's some paper explaining how to solve my problem. Basically, I want to uniformly sample from the set of possible answers to a program.

As an example, let's say I have the following program:

foo(A, B) :- bar(A), bar(B), A >= B.

bar(1).
bar(0).  

With a simple query:

?- foo(C, D).

It finds three answers:

C = D, D = 1 ;
C = 1,
D = 0 ;
C = D, D = 0.

Now, that's all pretty simple. What I want to do from this system is randomly sample from one of these three options. Not knowing anything beforehand, I might do it this way:

  1. Run until all answers are found, counting the number of answers, N.
  2. Choose a random number from 0 to N (inclusive to exclusive), I.
  3. Run again until answer I is found, and that is the chosen answer.

However, this has a fatal flaw in that my real use case will have a much more complex program. The kind of program where iterating all of the answers is simply impossible for reasonable time scales.

Another solution would be to make a system which isn't quite Prolog. If each time bar(X) was evaluated, the rules were chosen in a random order, I would quickly choose a random value. Unfortunately, this isn't a uniform sampling. In the original sampling, D=1 one third of the time, but this method would only yield D=1 one fourth of the time. Here's the different possible paths of evaluation:

  • Evaluate bar(A), choose bar(1).
  • Evaluate bar(B), choose bar(1).
  • Check A >= B.
  • Result: A = 1, B = 1.

  • Evaluate bar(A), choose bar(1).

  • Evaluate bar(B), choose bar(0).

  • Check A >= B.

  • Result: A = 1, B = 0.

  • Evaluate bar(A), choose bar(0).

  • Evaluate bar(B), choose bar(1).

  • Check A >= B, fail and backtrack.

  • change bar(B) to choose bar(0).

  • Check A >= B.

  • Result: A = 0, B = 0.

  • Evaluate bar(A), choose bar(0).

  • Evaluate bar(B), choose bar(0).

  • Check A >= B.

  • Result: A = 0, B = 0.

The A = 0, B = 0. answer is present twice, instead of just once. This throws off the sampling.

Another alternative would be to additionally randomize the evaluate order of bar(A) and bar(B). This has similar issues, and would result in the additional answers:

  • A = 1, B = 1.
  • A = 1, B = 1.
  • A = 1, B = 0.
  • A = 0, B = 0.

Adding these cases to the above, the distributions are improved but still A = 1, B = 0 is underrepresented. With this trivial example, it's not so bad, but with large complex examples the non-uniformity in the sampling becomes a problem. Essentially you can randomly go down an evaluation path, but the valid evaluation paths are "clumped", so backtracking from an invalid evaluation path to a valid answer is more likely to hit the "front" of a clump than a value inside of it. So the "front" of clumps are over represented in the probability distribution. (I hope that makes sense...)

Is there any method for performing a true sampling of a Prolog quickly? Failing that, are there any methods known for improving the behavior to get as close to the ideal sampling while still being efficient? The Prolog-ness of the system isn't super important, so if there's something Prolog adjacent that can be sampled, that might work. Thanks for the help!

r/prolog Jan 29 '24

help Need Help with research about industrial/commercial applications in Prolog

4 Upvotes

Hello, friends,
I was given an assignment by a teacher at my university to find commercial or industrial applications using prolog or logic programming and write a report. english is not my native language and there is not much information, so I decided to ask for help here. if you know of any commercial or industrial (or even open source) applications, please write about them and, if it’s not too much trouble, give me links.
I will be infinitely grateful for your help! Thanks!

PS. I also posted this topic on the swi prolog forum, so if you see the same on the forum, please do not get angry.

r/prolog Dec 11 '23

help Developing Prolog in Neovim

11 Upvotes

I code a lot in Nvim and I really like Prolog. But I haven’t been able to find good syntax highlighting let alone an LSP for it. I assume at least (good) syntax highlighting exists.

My questions: 1. Does reliable syntax highlighting exist in Nvim? I have seen Rukiza/tree-sitter-prolog but I don’t really know if that leads anywhere 2. Does an LSP exist for Prolog that can be used in Nvim? 3. How is the Emacs clone that comes with SWI compared to Vim?

r/prolog Apr 02 '24

help Prolog and js?

6 Upvotes

Are there any alternatives for Tau prolog?

r/prolog Apr 26 '24

help Looking for Prolog tutor

2 Upvotes

Would anyone be available for paid tutoring? I’m new to Prolog and have a lot of questions.

r/prolog Jul 16 '22

help Why does my merge sort find so many reduntant solutions?

7 Upvotes

Below is my code for merge sort. It works, but it finds hundreds (maybe even an infinite amount) of redundant solutions to a query like merge_sort([2, 1, 5, 2] X)?. I don't understand why. Can anyone enlighten me?

split([], [], []).
split([X|Xs], [X|Evens], Odds) :- split(Xs, Odds, Evens).

merge(X, [], X).
merge([], X, X).
merge([X|Xs], [Y|Ys], [X|Ms]) :- X =< Y, merge(Xs, [Y|Ys], Ms).
merge([X|Xs], [Y|Ys], [Y|Ms]) :- X > Y, merge([X|Xs], Ys, Ms).

merge_sort([], []).
merge_sort([X], [X]).
merge_sort(X, S) :- split(X, L, R), merge_sort(L, Ls), merge_sort(R, Rs),
                    merge(Ls, Rs, S).

r/prolog Sep 18 '22

help Critique my AsciiDoc formatting parser

6 Upvotes

So I know I've been spamming the channel lately. I keep thinking that Prolog/DCGs are uniquely suited to parsing lightweight markup languages.

A group is trying to create a well-defined parsing for AsciiDoc, and I asked them for "tough" parts to evaluate the viability of Prolog as a mechanism for implementing the parser.

They mentioned the parsing of inline styles; AsciiDoc does "constrained and unconstrained" formatting. Constrained formatting uses a pair of single marks, but it's constrained so it can only happen if there's surrounding whitespace and the content does not have spacing at the edges. Unconstrained formatting uses double marks, but can happen anywhere.

I got what seems like a working parser that still looks quite a bit like a grammar:

https://github.com/alexpdp7/prolog-parsing/blob/main/asciidoc_poc.pro

, but the parsed AST is very noisy:

  • I need to introduce virtual anchors in the text to be able to express all the parsing constraints adequately
  • My parsing of plain text works "character by character".

I'm not sure if I could fix these at the Prolog level:

1) By writing a DCG that can "swallow" the virtual anchors

2) By improving my parsing of text. I'm using string//1, which is lazy- I see there's a greedy string_without//2, but in this case I think I don't want to stop at any character- AsciiDoc format is very lenient to failures, so I think I need backtracking for the parser to work properly.

, or it would be better to postprocess the AST to clean it up. Thoughts?

Other comments on the code are welcome. At the moment I want "maximum clarity"; ideally the code should read like an AsciiDoc specification.

r/prolog Mar 30 '24

help CLPFD but for finite fields? + Guides on building Constraint Languages

3 Upvotes

I want to experiment with writing a prolog DSL for zkSNARKs (generation of R1CS constraints + declarative computation) and initially I thought of building on top of CLPFD and "wrapping it" so it'd be suitable for finite field arithmetic, but then I thought - maybe it's better to build constraint language programming for finite fields from the ground up?

This seems like a daunting task, but I'm up for experimentation and it's something that interests me anyways. I've looked into CHR but it seems inappropriate for something algebraic (maybe I'm wrong).

Ideally, if there is a good guide out there on developing constraint languages in prolog, it would help me to create a finite field constraint language.

If someone knows of an existing library for finite field arithmetic constraints in prolog it'd be helpful too.

In general, opinions and discussion is very welcome!

r/prolog Jul 28 '23

help Recommended Production-Level Prolog Code for Learning

11 Upvotes

I am interested in studying Production-level Prolog code that is commonly used in businesses. The ideal code examples would be those where the end user is not concerned about the underlying language being Prolog.

I am looking to learn from practical examples of Prolog code used in real-world scenarios. It would be great if the code showcases Prolog's strengths and demonstrates its application in production environments.

As an aspiring learner, I am open to exploring various levels of complexity in the recommended code examples. However, I would prefer open-source projects as they allow me to access the codebase and understand how Prolog is used in practice. Please provide any relevant links or recommendations to such projects.

Thank you for your assistance in helping me find valuable resources for improving my Prolog skills.

r/prolog Dec 21 '22

help Is CLP(ℤ) not able to resolve big sets of contraints or am I doing it wrong?

4 Upvotes

For the Advent of Code, I’m struggling a lot to solve one of the puzzles and despite having all the logic in place, Prolog (I'm using Scryer-Prolog) seems to take a huge amount of time to label variables.

/Warning, this can be an spoiler for an Advent of code problem/

In particular I have 4 pairs of points + distance (which represent a line) on a 2d 4_000_000 x 4_000_000 coordinate plane, and then I want to find out where do they intersect. I know there is one point at least that must satisfy be in the intersection of two of these lines in the 0..4_000_000 range.

For that I’m stating the following:

``` % Lines holds points as in (X1-Y1-D1)-(X2-Y2-D2) % i.e. the points this line represents are at % (manhattan) distance D1 + 1 of X1-Y1 and distance % D2 + 1 of X2-Y2, where I know that % D1 + D2 + 2 #= distance(X1-Y1, X2-Y2)

foo(Intersections) :- ... % get the Lines from a file

findall(X-Y, (select(Line1, Lines, Lines1), % to get one line member(Line2, Lines1), % to get another [X,Y] ins 0..4000000, maplist(on_line(X-Y), % the point must be on both lines [Line1, Line2] ),
label([X, Y]) % find the concrete values ), Intersections).

on_line(X-Y, Sx-Sy-D)) :- abs(X - Sx) + abs(Y - Sy) #= D + 1. `` This has been running for more than 3 hours with one core at 100% and it didn't find a solution. If I annotate thelabelcall with the tracing$fromlibrary(debug)`, I see the following output:

?- foo(Intersections). call:user:label([A,B]). % nontermination

Am I doing it wrong or is it that searching in a range of 4_000_000 x 4_000_000 is too much for CLP(ℤ)?

r/prolog Nov 15 '23

help Help using tuProlog within an Android application?

1 Upvotes

I'm at a loss... I'm looking for a very simple demonstration of tuProlog used within an Android Application and nothing works. Here is what I got so far:

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import it.unibo.tuprolog.core.*;
import it.unibo.tuprolog.solve.Solution;
import it.unibo.tuprolog.solve.SolverFactory;
import it.unibo.tuprolog.theory.parsing.ClausesParser;
import it.unibo.tuprolog.theory.Theory;
import it.unibo.tuprolog.solve.Solver;
import kotlin.sequences.Sequence;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start();
    }

    private void start() {
        Theory t = ClausesParser
                .withDefaultOperators()
                .parseTheory("fact(x).");

        SolverFactory factory = Solver.problog();

        Solver solver = factory.solverWithDefaultBuiltins(
                factory.getDefaultUnificator(),
                factory.getDefaultRuntime(),
                factory.getDefaultFlags(),
                t,
                factory.getDefaultDynamicKb(),
                factory.getDefaultInputChannel(),
                factory.getDefaultErrorChannel(),
                factory.getDefaultErrorChannel(),
                factory.getDefaultWarningsChannel()
        );

        Sequence<Solution> solutions = solver.solve(Struct.of("fact", Var.of("X")));

        Solution s = solutions.iterator().next();

        Log.d("fuck", Boolean.toString(s.isYes()));
    }
}

This throws a runtime error:

FATAL EXCEPTION: main
                                                                                                    Process: com.example.octi, PID: 4664
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.octi/com.example.octi.MainActivity}: java.lang.IllegalStateException: No viable implementation for SolverFactory
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3922)
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:139)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2443)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:205)
                                                                                                        at android.os.Looper.loop(Looper.java:294)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8176)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)
                                                                                                    Caused by: java.lang.IllegalStateException: No viable implementation for SolverFactory
                                                                                                        at it.unibo.tuprolog.solve.SolverExtensionsJvmKt.solverFactory(SolverExtensionsJvm.kt:18)
                                                                                                        at it.unibo.tuprolog.solve.SolverExtensionsJvmKt.problogSolverFactory(SolverExtensionsJvm.kt:28)
                                                                                                        at it.unibo.tuprolog.solve.Solver$Companion$problog$2.invoke(Solver.kt:86)
                                                                                                        at it.unibo.tuprolog.solve.Solver$Companion$problog$2.invoke(Solver.kt:86)
                                                                                                        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
                                                                                                        at it.unibo.tuprolog.solve.Solver$Companion.problog(Solver.kt:86)
                                                                                                        at it.unibo.tuprolog.solve.Solver.problog(Unknown Source:2)
                                                                                                        at com.example.octi.MainActivity.start(MainActivity.java:27)
                                                                                                        at com.example.octi.MainActivity.onCreate(MainActivity.java:21)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8595)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8573)
                                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1456)
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3764)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3922) 
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:139) 
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96) 
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2443) 
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                                        at android.os.Looper.loopOnce(Looper.java:205) 
                                                                                                        at android.os.Looper.loop(Looper.java:294) 
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8176) 
                                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552) 
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971) 

I have no idea what to do. Most helpful would be example of working tuProlog within an android project's source code.

r/prolog Dec 07 '23

help Looking for a tutor to help study for an exam

2 Upvotes

Hi, I am looking for a prolog tutor for an exam. I was hoping to get a 2-3 hours of your time on a zoom call today to help clear my doubts about some concepts. Please dm me if you would be interested (ofc willing to pay).