1
votes

I'm having a little trouble understanding list recursion and modification in Prolog. I'm trying to take a list of lists, then with each list, multiply each element in the list by the last element.

Here's a snippet of my code:

    /*Find the last element of a list*/
    lastelement(X,[X]).
    lastelement(X,[_|L]) :- lastelement(X,L).

    /*Multiply two lists together*/
    multiplication(M1,M2,M1*M2).

    /*Take a list, find the last element and multiply every part of that list by that  element*/
    /*Attach modified list to X*/
    modifyL([],X) :- X is [].
    modifyL([First|Tset],X) :- lastelement(Y,First),
    multiplication(Y,First,MFirst),
    modifyL([Tset],X),
    append(X,MFirst,X).

When I try any list of lists, however, all I get is false. Can someone give me any pointers on list recursion that could help further understand this problem?

1
which implementation are you using?Janus Troelsen
I'm currently using SWI Prolog version 5.10Frustrated_Grunt

1 Answers

1
votes
modifyL([],X) :- X is [].

This doesn't do what you think, is is used to get the result of an arithmetic evaluation.

you can write

 modifyL([],X) :- X = [].

or simply

 modifyL([],[]).

When you work with a list, and you repeat the same process to each element of this list you can use maplist which is exactly design for that. the template is maplist(Goal, L1 L2).

modify(L1, L2) :-
  maplist(multiply_one_list,L1, L2).

multiply_one_list works with a list, you it can be written like that :

multiply_one_list(L_in, L_out) :-
  % getting last argument
  reverse(L_in, [Last | _]),
  % multiply each element of the list by
  % the last element, one more maplist !
  maplist(multiply_one_element(Last), L_in, L_out).

multiply_one_element(Last, In, Out) :-
  Out is In * Last.