prologmaplist

Wrap every element from a list


How do you wrap every element from a list?

I have something like this (2*3*4*...)^6

How do I make a list with this output: 2^6 * 3^6 * 4^6 * ...

I was thinking on something simple using maplist but I am not sure how to send a parameter to the function in the first argument.

simplify(X^Y,R):- X=..[*|Args], maplist(?^Y, Args, Args2), R=..[*|Args2], !.

:- simplify((2*x)^6, (2^6) * (x^6)). %should be true

Using Swi-prolog by the way


Solution

  • Your input data structure does not contain any lists, it is a nested structure with numbers at the leaves:

    ?- write_canonical(2*3*4*5).
    *(*(*(2, 3), 4), 5)
    

    Therefore maplist isn't much use here. Instead, write a simple recursive predicate to traverse (and reconstruct) the recursive data structure:

    simplify(N, Exp, N^Exp) :-
        number(N).
    simplify(L*R, Exp, LExp*RExp) :-
        simplify(L, Exp, LExp),
        simplify(R, Exp, RExp).
    

    The code structure follows the data structure. Example run

    ?- simplify(2*3*4*5, 6, E).
    E = 2^6*3^6*4^6*5^6
    Yes (0.00s cpu)