Search code examples
prologmaplist

Implement my own maplist in Prolog?


I want to implement my own maplist in Prolog .

Given the following :

myMaplist(Goal, [Elem1|Tail1], [Elem2|Tail2]) :-
        apply(Goal, [Elem1, Elem2]), 
        myMaplist(Goal, Tail1, Tail2).

What is the apply operator , and how can I replace it with something that is not a library system call ?


Solution

  • if your Prolog has call/N, use it:

    myMaplist(Goal, [Elem1|Tail1], [Elem2|Tail2]) :-
            call(Goal, Elem1, Elem2), 
            myMaplist(Goal, Tail1, Tail2).
    

    otherwise build the call with univ, and use call/1

    myMaplist(Goal, [Elem1|Tail1], [Elem2|Tail2]) :-
            Pred =.. [Goal, Elem1, Elem2],
            call(Pred),
            myMaplist(Goal, Tail1, Tail2).
    

    edit thanks to @false for pointing out that I must correct. To be true I posted that code without test, nevertheless I surely overlooked the bug... Here a correction

    myMapList(_, [], []).
    myMapList(Goal, [Elem1|Tail1], [Elem2|Tail2]) :-
        Goal =.. [P|A],
        append(A, [Elem1, Elem2], Ac),
        Pred =.. [P|Ac],
        call(Pred),
        myMapList(Goal, Tail1, Tail2).
    

    test:

    ?- myMapList(myMapList(=),[[1,2,3],[a,b,c]],L).
    L = [[1, 2, 3], [a, b, c]] .