Search code examples
listrecursionprologmirror

mirroring a list in prolog


My wanted output is this:

?- mirror ([1,2], [] , X ).
X= [1,2,2,1]

What I have so far:

mirror(L,R,X):- L is R , [R| revertList(L,X)] .

I cant think of how this works, please help me


Solution

  • It is not very different from reversing a list, but how you write it is not going to work. I googled "Prolog is" and after maybe 10 seconds I see that is/2 is for arithmetic expressions. I also don't know how you think that you can put predicate but maybe it is not possible? If you want to just append then you can use append to append the mirror reversed list to the end of the original list to get the final "mirror" result:

    mirror(X, Y) :- reverse(X, R), append(X, R, Y).
    

    but this is too easy? So I wonder maybe there is more to this question? I don't know why you have three arguments when you only need two arguments? Maybe you thought that you can use an accumulator to reverse the list because to reverse a list you use accumulator like this?

    list_rev(L, R) :- list_rev(L, [], R).
    
    list_rev([], R, R).
    list_rev([X|Xs], Ys, R) :-
        list_rev(Xs, [X|Ys], R).
    

    But this is very easy to google, I just googled it and found it, so maybe you googled it too and you didn't like it? To get "mirrored" you just need to keep the original list too, like so:

    list_mirrored(L, M) :- list_mirrored(L, [], M).
    
    list_mirrored([], M, M).
    list_mirrored([X|Xs], Ys, [X|Zs]) :-
        list_mirrored(Xs, [X|Ys], Zs).
    

    I wasn't sure if this is correct and I googled "Prolog append" and this is how it is done.