0

Hello I have a predicate that returns example equalisation for given list

equalisation([1,2,3,4,12],L).
L = (1=2-3* (4/12)) 

now I want to change this result into a list like this:

L = [1,=,2,-,3,*,4,/,12]

How can I do that?

3
  • @Bender Why do you remove the tag term? It has a very specific meaning in Prolog
    – false
    Apr 8, 2022 at 18:49
  • Is there a more appropriate tag than [term]? That tag is currently being burninated. I could not find a more appropriate tag in regards to prolog's term component.
    – codewario
    Apr 8, 2022 at 18:51
  • 1
    Term might be replaced by prolog-term. But this would then be a new tag.
    – false
    Apr 8, 2022 at 19:01

2 Answers 2

3

The simplest solution would be to traverse a term creating a list of small lists, and then to flatten everything. However, the simplest solution is not the most elegant one - quoting the SWI Prolog flatten/2 manual:

Ending up needing flatten/3 often indicates, like append/3 for appending two lists, a bad design. Efficient code that generates lists from generated small lists must use difference lists, often possible through grammar rules for optimal readability.

So here is an alternative solution using difference lists:

t2l(Term, List) :- t2l_(Term, List-X), X = [].

t2l_(Term, [F|X]-X) :- Term =.. [F], !.
t2l_(Term, L1-L4) :- Term =.. [F, A1, A2], 
                     t2l_(A1, L1-L2), 
                     L2 = [F|L3], 
                     t2l_(A2, L3-L4).

Clearly, the current solution works only for binary operations. If operations with an arbitrary number of arguments are allowed, then another traversal of the arguments will be required.

0
1

Check out how the (=..)/2 operator works.

And if you wanna check that expressions are equal use (=:=)/2 instead of (=)/2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.