Skip to content

Commit

Permalink
Prolog.consult method updates (#177)
Browse files Browse the repository at this point in the history
* Added relative_to keyword argument to `Prolog.consult`
* `Prolog.consult` expands tilde character to the home directory
  • Loading branch information
yuce authored Oct 13, 2024
1 parent 349c02b commit 7f92e76
Show file tree
Hide file tree
Showing 16 changed files with 148 additions and 114 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ prolog.consult("knowledge_base.pl")
### Foreign Functions

```python
from __future__ import print_function
from pyswip import Prolog, registerForeign

def hello(t):
Expand All @@ -77,7 +76,6 @@ print(list(prolog.query("father(michael,X), hello(X)")))
### Pythonic interface (Experimental)

```python
from __future__ import print_function
from pyswip import Functor, Variable, Query, call

assertz = Functor("assertz", 1)
Expand Down
14 changes: 3 additions & 11 deletions examples/coins/coins.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
Expand All @@ -23,27 +21,21 @@

# 100 coins must sum to $5.00

from __future__ import print_function
from pyswip.prolog import Prolog

try:
input = raw_input
except NameError:
pass


def main():
prolog = Prolog()
prolog.consult("coins.pl")
prolog.consult("coins.pl", relative_to=__file__)
count = int(input("How many coins (default: 100)? ") or 100)
total = int(input("What should be the total (default: 500)? ") or 500)
for i, soln in enumerate(prolog.query("coins(S, %d, %d)." % (count, total))):
S = zip(soln["S"], [1, 5, 10, 50, 100])
print(i, end=" ")
for c, v in S:
print("%dx%d" % (c, v), end=" ")
print(f"{c}x{v}", end=" ")
print()
list(prolog.query("coins(S, %d, %d)." % (count, total)))
list(prolog.query(f"coins(S, {count}, {total})."))


if __name__ == "__main__":
Expand Down
13 changes: 2 additions & 11 deletions examples/coins/coins_new.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
Expand All @@ -23,19 +21,12 @@

# 100 coins must sum to $5.00

from __future__ import print_function
from pyswip import Prolog, Functor, Variable, Query


try:
input = raw_input
except NameError:
pass


def main():
prolog = Prolog()
prolog.consult("coins.pl")
prolog.consult("coins.pl", relative_to=__file__)
count = int(input("How many coins (default: 100)? ") or 100)
total = int(input("What should be the total (default: 500)? ") or 500)
coins = Functor("coins", 3)
Expand All @@ -47,7 +38,7 @@ def main():
s = zip(S.value, [1, 5, 10, 50, 100])
print(i, end=" ")
for c, v in s:
print("%dx%d" % (c, v), end=" ")
print(f"{c}x{v}", end=" ")
print()
i += 1
q.closeQuery()
Expand Down
11 changes: 1 addition & 10 deletions examples/draughts/puzzle1.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
Expand Down Expand Up @@ -35,19 +33,12 @@
# are four guards watching each wall. How can they be rearranged such
# that there are five watching each wall?"

from __future__ import print_function
from pyswip.prolog import Prolog


try:
input = raw_input
except NameError:
pass


def main():
prolog = Prolog()
prolog.consult("puzzle1.pl")
prolog.consult("puzzle1.pl", relative_to=__file__)

for soln in prolog.query("solve(B)."):
B = soln["B"]
Expand Down
13 changes: 4 additions & 9 deletions examples/hanoi/hanoi.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
Expand All @@ -21,7 +19,6 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import print_function
from collections import deque

from pyswip.prolog import Prolog
Expand Down Expand Up @@ -78,15 +75,13 @@ def draw(self):


def main():
N = 3
INTERACTIVITY = True

n = 3
prolog = Prolog()
tower = Tower(N, INTERACTIVITY)
tower = Tower(n, True)
notifier = Notifier(tower.move)
registerForeign(notifier.notify)
prolog.consult("hanoi.pl")
list(prolog.query("hanoi(%d)" % N))
prolog.consult("hanoi.pl", relative_to=__file__)
list(prolog.query("hanoi(%d)" % n))


if __name__ == "__main__":
Expand Down
7 changes: 2 additions & 5 deletions examples/hanoi/hanoi_simple.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
Expand All @@ -21,7 +19,6 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import print_function
from pyswip.prolog import Prolog
from pyswip.easy import registerForeign

Expand All @@ -36,8 +33,8 @@ def notify(t):

prolog = Prolog()
registerForeign(notify)
prolog.consult("hanoi.pl")
list(prolog.query("hanoi(%d)" % N))
prolog.consult("hanoi.pl", relative_to=__file__)
list(prolog.query(f"hanoi({N})"))


if __name__ == "__main__":
Expand Down
9 changes: 3 additions & 6 deletions examples/sendmoremoney/money.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
# Copyright (c) 2007-2024 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -29,12 +27,11 @@
# So, what should be the values of S, E, N, D, M, O, R, Y
# if they are all distinct digits.

from __future__ import print_function
from pyswip import Prolog

letters = "S E N D M O R Y".split()
letters = list("SENDMORY")
prolog = Prolog()
prolog.consult("money.pl")
prolog.consult("money.pl", relative_to=__file__)
for result in prolog.query("sendmore(X)"):
r = result["X"]
for i, letter in enumerate(letters):
Expand Down
7 changes: 2 additions & 5 deletions examples/sendmoremoney/money_new.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
Expand Down Expand Up @@ -29,15 +27,14 @@
# So, what should be the values of S, E, N, D, M, O, R, Y
# if they are all distinct digits.

from __future__ import print_function
from pyswip import Prolog, Functor, Variable, call


def main():
letters = "S E N D M O R Y".split()
letters = list("SENDMORY")
prolog = Prolog()
sendmore = Functor("sendmore")
prolog.consult("money.pl")
prolog.consult("money.pl", relative_to=__file__)

X = Variable()
call(sendmore(X))
Expand Down
7 changes: 1 addition & 6 deletions src/pyswip/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-


# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
# Copyright (c) 2007-2024 Yüce Tekol and PySwip Contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
Expand All @@ -22,8 +19,6 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


# PySwip version
__VERSION__ = "0.3.1"

from pyswip.prolog import Prolog as Prolog
Expand Down
8 changes: 1 addition & 7 deletions src/pyswip/core.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
# -*- coding: utf-8 -*-


# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
# Copyright (c) 2007-2024 Yüce Tekol and PySwip Contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
Expand All @@ -22,8 +18,6 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import print_function

import atexit
import glob
import os
Expand Down
29 changes: 4 additions & 25 deletions src/pyswip/easy.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
# -*- coding: utf-8 -*-


# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
# Copyright (c) 2007-2024 Yüce Tekol and PySwip Contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
Expand All @@ -22,18 +18,10 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


from pyswip.core import *


# For backwards compability with Python 2 64bit
if sys.version_info < (3,):
integer_types = (
int,
long,
)
else:
integer_types = (int,)
integer_types = (int,)


class InvalidTypeError(TypeError):
Expand Down Expand Up @@ -146,17 +134,8 @@ def __hash__(self):
return self.handle


# support unicode also in python 2
try:
isinstance("", basestring)

def isstr(s):
return isinstance(s, basestring)

except NameError:

def isstr(s):
return isinstance(s, str)
def isstr(s):
return isinstance(s, str)


class Variable(object):
Expand Down
43 changes: 34 additions & 9 deletions src/pyswip/prolog.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
# -*- coding: utf-8 -*-


# prolog.py -- Prolog class
# Copyright (c) 2007-2012 Yüce Tekol
# Copyright (c) 2007-2024 Yüce Tekol and PySwip Contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
Expand All @@ -22,8 +18,34 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


from pyswip.core import *
from typing import Union
from pathlib import Path

from pyswip.utils import resolve_path
from pyswip.core import (
SWI_HOME_DIR,
PL_STRING,
REP_UTF8,
PL_Q_NODEBUG,
PL_Q_CATCH_EXCEPTION,
PL_Q_NORMAL,
PL_initialise,
PL_open_foreign_frame,
PL_new_term_ref,
PL_chars_to_term,
PL_call,
PL_discard_foreign_frame,
PL_new_term_refs,
PL_put_chars,
PL_predicate,
PL_open_query,
PL_next_solution,
PL_copy_term_ref,
PL_exception,
PL_cut_query,
PL_thread_self,
PL_thread_attach_engine,
)


class PrologError(Exception):
Expand Down Expand Up @@ -180,8 +202,11 @@ def retractall(cls, term, catcherrors=False):
next(cls.query(term.join(["retractall((", "))."]), catcherrors=catcherrors))

@classmethod
def consult(cls, filename, catcherrors=False):
next(cls.query(filename.join(["consult('", "')"]), catcherrors=catcherrors))
def consult(
cls, filename: str, *, catcherrors=False, relative_to: Union[str, Path] = ""
):
path = resolve_path(filename, relative_to)
next(cls.query(str(path).join(["consult('", "')"]), catcherrors=catcherrors))

@classmethod
def query(cls, query, maxresult=-1, catcherrors=True, normalize=True):
Expand Down
Loading

0 comments on commit 7f92e76

Please sign in to comment.