Search code examples
pythonjsonprologswi-prolog

Python: convert dictionary from swiplserver


I am using swiplserver for using prolog queries in python. Within that queries I get dictionaries of this kind:

to_translate = {'A': 'p', 'B': '_', 'C': 'q', 'Z': {'→E': {'args': [['p', {'args': ['p', 'q'], 'functor': '→'}], 'q'], 'functor': '⊦'}}}

In the prolog file I just defined some xfy operators (e.g. ⊦ and →). My aim now is to translate the dictionary in the following way (is the same as the natural output of prolog would give me):

result = {'A': 'p', 'B': '_', 'C': 'q', 'Z': {'→E': '[p, (p → q)] ⊦ q'}}

If ⊦ wouldn't be in the list of my operators, the result would be:

result = {'A': 'p', 'B': '_', 'C': 'q', 'Z': {'→E': '⊦([p, (p → q)], q)'}}

I've heard swiplserver uses JSON to generate the dictionaries itself. Maybe that is the key and the problem is much easier to solve as I think.

Hope you can give me some quick tip or some solution about that.


Solution

  • I think you are asking how to convert the JSON format returned by swiplserver into a Prolog string?

    There is a swiplserver function json_to_prolog that will do this, but it currently only generates terms like +(b, c) as opposed to b + c which is not quite what you're looking for, but may be helpful?

    from swiplserver import *
    
    print(json_to_prolog({'args': [['p', {'args': ['p', 'q'], 'functor': '→'}], 'q'], 'functor': '⊦'}))
    

    Running that gives:

    '⊦'([p, '→'(p, q)], q)